How to add comments in C++ with example

Introduction :

Comments are important. It makes the code more readable. Comment is supported in all programming languages. In C++, comments are categorized into two types. In this tutorial, I will show you how to write comments in a C++ program. Always try to write comment in your code. It is a good development practice.

Two types of comments: Line and Block comment :

Two types of comments are available in C++: line and block comments. Line comment is used for single-line comments and Block comment is used for multi-line comments. Following are the syntax of these two types of comments :

// line comment example
/* block comment example */

For line comments, the comment starts from the slash pairs (//) and ends at the end of this line. For block comment, it starts at /* and ends at */. We can multiple lines between these characters. For example :

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello"; // print hello
    cout << "World"; /* print world 
                        don't print hello here.
                        this is the last print statement */
}

C++ comments example

We are using both single-line and multi-line comments in this example.

It will throw one error if you write two lines for the line comment :

C++ comments example

The C++ compiler reads the second line as an expression and throws the error. Similarly, don’t forget to close the multi-line comments. It will comment out everything from its start point.

C++ comments example

In this example, the multi-line comment has commented out all.

Commenting is a good development practice. Try to add useful comments always with writing code. Comments help a lot while maintaining a large project.