Comments in C++:
A comment is an explanation or description of the source code of the program. It helps a developer explain the logic of the code and improves program readability. They are generally ignored by compilers and interpreters.
Why do we need comments:
The code tells you what is being done and how, but it doesn’t tell you why it has been done. Take an example where you have initialized a variable of a data type. But someone seeing your code the first time might not know why you have initialized it.
Comments are important so that the person maintaining the program will be able to tell exactly what each section of the code does. Sometimes the programmer maintaining the source code might even forget what the line of code does in a whole program after a year of completion of the project.
Types of Comments in C++:
There are two types of comments in C++;
- Single-line comment.
- Multi-line comment.
Single Line comment:
A single-line comment starts and ends in the same line. To write a single-line comment, we can use the // symbol. It is applicable for a single line only. Compliers ignore the line which has been commented.
Syntax:
// Single Line comment
Code:
C++ Code
#include<iostream>
using namespace std;
int main() {
//Single line comment
cout << "Takeuforward" << endl;
return 0;
}
Single Line comment at the end of line
C++ Code
#include<iostream>
using namespace std;
int main() {
cout << "Takeuforward" << endl; //Single line comment at end of line
return 0;
}
Multi-Line comment:
When we have to write comments in multiple lines, we can use the multi-line comment. Mutli line comment starts with forwarding slash / and asterisk (/*), and ends with asterisk and forward-slash (*/).
Syntax:
/* Comment starts Multi line comment Continues */ Comment ends
Code:
C++ Code
#include<iostream>
using namespace std;
int main() {
/* Multi line comments
are used to write documentation
or instructions in a brief*/
cout << "Takeuforward" << endl;
return 0;
}
Special thanks to Rushikesh Aadav for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article