How to Write C++ Comments

Commenting is an integral part of programming languages.

Although it does not add to the functionality of code, it is critical to the understanding of it. Both programmers and non-programmers need comments to make sense of the code at their own level. A comment in a programming language can be defined as a line written in a common language that explains what the code does or the purpose behind the code. It is a note that is inserted directly into the source code. Comments are written using proper syntax so that the compilers and interpreters skip it because they are not the part of code that functions. The purpose of writing comments in code is manifold. It is helpful not just for non-programmers in understanding the code but also for programmers long after they are done writing the code. Therefore, it is critical to include comments in the code as you write it and not postpone it to be done at the end of coding as you are likely to forget the thought process later.

Table of Contents

You can skip to a specific section of this C++ tutorial using the table of contents below:

Types of C++ Comments

There are two main comment types in C++: single-line comments and multi-line comments. There is another kind of single-line comment called an inline comment. These are explained below along with examples.

1. Single-line Comments

Single-line comments are the ones that last up to one line. These types of comments start with a double forward-slash (//).

Syntax:

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

Here’s a simple ‘Hello World!’ program to illustrate single-line comments.

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

Output:

Hello World!

2. Multi-line Comments

The comments that go on for multiple lines are called multi-line comments. There are two ways of writing multi-line comments. One way of doing it is by starting each line of comment by a double forward-slash (//).

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

However, this format can become tedious when the comment is longer. For a comment that goes on for a paragraph or multiple paragraphs, a different syntax is used. A multi-line comment starts with /* and ends with a */.

/*
This is how a multi-line comment is made
in C++.  All the lines wrapped in a pair of
forwarding slash and a star are ignored. This
line is ignored by the compiler and so is
this line.
*/

A single-line comment can be nested inside a multi-line comment. However, a multi-line comment cannot be nested inside another multi-line comment.

/* The comment starts here /* and */ this is outside the comment */
// The comment in above line ends at first */ and not the second */

3. Inline Comments

This is type of single-line comment. When a line of code is followed by a comment within same line, it is called inline comment. Below is the example to make it clearer:

include <iostream>
int main()
{
	cout << Welcome to lessons in Cpp. << endl; 	// this is an inline comment
	return 0;
}

Output:

Welcome to lessons in Cpp.

Documentation Comments

Before each file or function begins, block comments are used. These comments contain information pertaining to the file that follows. They are created as follows:

  • The first line is indented to align with code below the comment.
  • Include details of the purpose of class or function that follows.
  • Leave one line blank between description and the list of tags.
/*
	CS-11 Asn 2, checks.cpp
	Purpose: Calculate the total of 10 checks
 
	@author Nick McCullum
	@version 2.3 03/05/2020
*/

A properly documented source code has such block comments that contain information on files and functions. Below is an example:

/**
	CS-11 Asn 19
	spherecircle.cpp
	Purpose: Calculates the area of a circle and the volume
	of a sphere.
	@author Nick McCullum
	@version 1.1 5/12/2020
*/
 
#include <iostream>
#include <cmath>
using namespace std;
const double PI = 3.14159;
 
/*
	Returns the area of a circle with the given radius.
	@param radius The radius of the circle.
	@return The area of the circle.
*/
double area(double radius);
/*
	Returns the volume of a sphere with the given radius.
	@param radius The radius of the circle.
	@return The volume of the sphere.
*/
double volume(double radius);
// Controls the program.
int main(void) {
	double radius_of_circlesphere, area_of_circle, volume_of_sphere;
 
	cout << "Enter the radius of a circle\n"
        	<< "and a sphere (in centimetres): ";
	cin >> radius_of_ circlesphere;
 
	area_of_circle = area(radius_of_ circlesphere);
	volume_of_sphere = volume(radius_of_ circlesphere);
 
	cout << "Radius = " << radius_of_ circlesphere << " centimetres\n"
        	<< "Area of circle = " << area_of_circle
        	<< " square inches\n"
        	<< "Volume of sphere = " << volume_of_sphere
        	<< " cubic centimetres\n";
 
	return 0;
}
 
// Returns the area of a circle with the given radius.
double area(double radius) {
	return (PI * pow(radius, 2));
}
// Returns the volume of a sphere with the given radius.
double volume(double radius) {
	return ((4.0 / 3.0) * PI * pow(radius, 3));
}

Why Write Comments in C++?

It might seem to you that comments are not that important. However, commenting is a significant aspect of programming. Now that you have learned the syntax of single and multi-line comments, let me tell you more about what makes C++ comments critical to good code.

1. Easier to Understand your Code at Any Point in Time

For a programmer, it becomes a little difficult to remember what the code does, especially when the codes are long and time to finish it is less.

At times when a programmer is in rush, he might give variables a temporary name which he has to correct later. In such cases, if you do not leave a comment, it can be a disaster because you will not remember later that what is what.

Some programmers may think of completing the code first and writing comments once that is done. This almost never works because by the time code is complete, they will have lost track of it and they are tired. The best way to go about commenting is by doing it as you write the code.

2. Others can Understand the Code without Reaching out to Developer

Most of the programs are quite long of about 20,000 lines and a single developer cannot complete the task. Multiple developers come together to complete the task. Different developers work on different parts of code and need to refer to each other’s work. In such a scenario, comments are important for them to make sense of the code that they have not developed. Using comments, they can skim through the code and understand it. Also, it helps in a smooth transition if a project has to be handed over to another person completely.

Best Commenting Practices

I wanted to conclude this tutorial by going through some widely-held best practices related to placing useful comments within a codebase.

1. Keep Your Comments Readable

The purpose of comments is simply to explain the purpose of code to programmers and non-programmers alike. Therefore, it is important that C++ comments are readable. Avoid using jargon in comments and keep the language simple and readable.

2. Whitespace Between Code and Comments is Important

This applies to both inline and separate comments. For inline comments, leave two to three blank spaces between the code and comment. For separate comment lines of blocks, leave a single line blank to separate code from comment. This is important to keep the code easy to read when skimming through it.

3. Comment as You Go

As explained earlier, make comments as you go on writing the code. Do not postpone comment writing until the code is done to avoid confusion and blunders that can result in buggy code.

4. Do No Explain the Obvious

Do not write comments for when code is clear. Some code lines and self-explanatory and comments should be omitted in such places, as shown below.

cout<< Hello World!;  // Prints Hello World!

In the code above, it is obvious that it prints Hello World! to console. Mentioning the same in the comment was unnecessary.

5. Do Not Use Comments to Explain the Problematic Code

Such comments are also called smelly comments. These are the comments that give a longer explanation of code when, in fact, code needs fixing. No amount of commenting can make it right when the problem is with code and will only make the code bulky.

Final Thoughts

A well-documented code is one with informative and concise comments. All languages allow commenting in some form. Without comments, a person reading the code might get confused. Therefore, good programmers are good at writing comments too.

If you enjoyed this article, be sure to join my Developer Monthly newsletter, where I send out the latest news from the world of Python and JavaScript:
Written on June 27, 2020