C++ Comments
Comments in a program are explanatory statements that you can include in your C++ code to enhance the readability of the source code. All programming languages allow some form of comments.
C++ supports single-line and multi-line comments. All characters inside a comment are ignored by the C++ compiler.
C++ comments typically come in two forms:
//
- Generally used for single-line comments./* ... */
- Generally used for multi-line comments.
Comments start with //
and continue until the end of the line. For example:
Example
#include <iostream>
using namespace std;
int main() {
// This is a comment
cout << "Hello World!";
return 0;
}
They can also be placed after a statement:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!"; // Outputs Hello World!
return 0;
}
When the above code is compiled, the compiler ignores // This is a comment
and // Outputs Hello World!
, and the final output will be:
Hello World!
C++ comments start with /*
and end with */
. For example:
#include <iostream>
using namespace std;
int main() {
/* This is a comment */
/* C++ comments can also
* span multiple lines
*/
cout << "Hello World!";
return 0;
}
Inside /*
and */
comments, the //
characters have no special meaning. Inside //
comments, the /*
and */
characters also have no special meaning. Therefore, you can nest one type of comment within another, like so:
/* Comment for outputting Hello World
cout << "Hello World"; // Outputs Hello World
*/