There are two ways to put comments in C++ code:
//
starts a single-line comment which ends at newline:
int main()
{
// This is a single-line comment
int a; // this also is a single-line comment
int i; // this is another single-line comment
}
Block comments can span multiple lines. They start with /*
and end with */
.
int main()
{
/*
This is a block comment.
*/
int a;
}
Block comments can also start and end within a single line. For example:
void SomeFunction(/* argument 1 */ int a, /* argument 2 */ int b);
As with all programming languages, comments provide several benefits:
However, comments also have their downsides:
The need for comments can be reduced by writing clear, self-documenting code. A simple example is the use of explanatory names for variables, functions, and types. Factoring out logically related tasks into discrete functions goes hand-in-hand with this.