Writing good comments is one of the most important skill for software developers.

Great commenting requires you to strike a delicate balance. On the one hand, your comments should allow your code to be interpretable by outside users. On the other hand, too many comments can add bloat to your code and ultimately make it harder to understand.

In this tutorial, you’ll learn how you write comments in C++. You’ll learn both the technical aspects of including comments in your code as well as professional guidelines on what types of comments you should include (and avoid).

Types of C++ Comments

There are two main comment types in C++:

  • single-line comments
  • multi-line comments

There is also another kind of single-line comment called an inline comment. We’ll explore each of these comment types one-by-one.

1. Single-line Comments

As their name implies, single-line comments are comments that can last up to one line. These types of comments start with a double forward-slash (//) in C++.

Here’s an example of a single-line comment in C++:

// this is a single-line comment in C++

Let’s consider a more realistic example. Here’s a simple C++ ‘Hello World!’ program that includes single-line comments.

// Cpp single-line comment example
#include <iostream>
int main()
{
 	// Hello World program in cpp  
	cout << "Hello World!" << endl;
	return 0;
}

Here the output of this code:

Hello World!

2. Multi-line Comments

Comments that continue for multiple lines are called multi-line comments.

There are two ways of writing multi-line comments in C++. One way is by starting each line of comment by a double forward-slash (//), which is equivalent to writing one single-line comment immediately after another.

Here is an example of this:

// This is an example of multi-line
// comments using the single-line
// commenting format.

This syntax is the most straightforward method for writing multi-line comments in C++. However, this format can be tedious with very long comments.

For a comment that lasts for a paragraph or more, it’s better to use a different syntax. The other method for writing C++ comments involves starting the comment with /* and ending the comment with */.

Here’s an example of this syntax in action:

/*
This is how a multi-line comment is made
in C++.  The multi-line comment is wrapped in a pair of
"/*" and "*/" operators. These lines are
ignored by the C++ compiler.
*/

#c++ #programming-c #cplusplus

How to Write C++ Comments
1.30 GEEK