A comment is text that the compiler ignores but is useful for programmers. Comments are normally used to annotate code for future reference. The compiler treats them as white space. Occasionally, comments are used to render certain lines of code inactive for test purposes; however, the #if/#endif preprocessor directives work better for this.
A C++ comment is written in one of the following ways:
The /* (slash, asterisk) characters, followed by any sequence of characters (including new lines), followed by the */ characters. This syntax is the same as ANSI C.
The // (two slashes) characters, followed by any sequence of characters. A new line not immediately preceded by a backslash terminates this form of comment. Therefore, it is commonly called a “single-line comment.”
The comment characters (/*, */, and //) have no special meaning within a character constant, string literal, or comment. Comments using the first syntax, therefore, cannot be nested. Consider this example:
/* Intent: Comment out this block of code.
Problem: Nested comments on each line of code are illegal.
FileName = String( "hello.dat" ); /* Initialize file string */
cout << "File: " << FileName << "\n"; /* Print status message */
*/
The preceding code will not compile because the compiler scans the input stream from the first /* to the first */ and considers it a comment. In this case, the first */ occurs at the end of the Initialize file string comment. The last */, then, is no longer paired with an opening /*.
Note that the single-line form (//) of a comment followed by the line-continuation token (\) can have surprising effects. Consider this code:
#include <stdio.h>
int main()
{
printf( "This is a number %d", // \
5 );
return 0;
}
After preprocessing, the preceding code appears as follows:
#include <stdio.h>
int main()
{
printf( "This is a number %d", // 5 );
return 0;
}
Because the single-line comment causes all further text on the same logical line to be considered a comment, the preceding program generates error messages.