C++ comments

Comments in C++ are the explanatory statements that helps a reader to understand the code. We can write single line as well as multi line comments in C++. Anything that is included inside a comment is ignored by the compiler.

Single line comment :

A single line comment can be created by start writing text after a double slash (//). A single line comment can be extended until the end of the line.

Example

#include<iostream>
using namespace std;
int main()
{
    //This will display Hello World
    cout<<"Hello World";
    return 0;
}

When the above program is executed, it will print the message Hello World. The line ‘This will display Hello World’ is a comment. It specifies the line number 5 and it would not be compiled.

Multi-line comments

A multiline comment start with /* and ends with */. Any text inside these two would be considered as a comment and would not be executed. In short a comment is not a part of our program.

#include<iostream>
using namespace std;
int main()
{
    /* The line below will print the 
    message Hello World on the screen.
    cout is an object of the class iostream
    and is used to display the output.*/

    cout<<"Hello World";
    return 0;
}

Output

Hello World

Note : You can put a comment anywhere in your program, before a line of code or after it. But it is a good practice to mention the comment before a line of code.

It is up to the programmer which approach to follow. Generally for shorter comments single line comments are used,  whereas multiline comments are used for comparatively longer comments.

Why it is a good practice to use comments?

  • Comments can be very helpful for a beginner programmer to understand the code written by someone else.
  • Comments can be used to temporary disable a part of our code.
  • Comments can be helpful for a programmer to understand what he did if he read his own written code after a long time.
  • Comments make the process of error finding very easy. A good documentation of a project should have comments about the algorithms.

Note : The syntax of both single line comment and multiline comments is the same for both C and C++.