Comments
suggest changeThere are two ways to put comments in C++ code:
Single-Line Comments
//
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
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);
Importance of Comments
As with all programming languages, comments provide several benefits:
- Explicit documentation of code to make it easier to read/maintain
- Explanation of the purpose and functionality of code
- Details on the history or reasoning behind the code
- Placement of copyright/licenses, project notes, special thanks, contributor credits, etc. directly in the source code.
However, comments also have their downsides:
- They must be maintained to reflect any changes in the code
- Excessive comments tend to make the code less readable
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.
Comment markers used to disable code
During development, comments can also be used to quickly disable portions of code without deleting it. This is often useful for testing or debugging purposes, but is not good style for anything other than temporary edits. This is often referred to as “commenting out”.
Similarly, keeping old versions of a piece of code in a comment for reference purposes is frowned upon, as it clutters files while offering little value compared to exploring the code’s history via a versioning system.