Home > C++ > Comments in C++

Comments in a program are explanatory statements that helps reader to understand source code. They must be written in a way that help reader to understand code.
E.g.
//setting value of x to 10.
int x=10;
now the above comment is not helping reader to understand code as reader can understand that x is set to 10 by reading this line
int x = 10;

e.g.
// We need to divide items by 2 here because they are bought in pairs
cost = items / 2 * storePrice;
Why comments are used?
In different programming languages Comments are used to tell the reader why the particular line of code is written. You can say that code tells us how a particular problem is solved but comments tell us why you did it. Comments help reader understand what program is really doing.

How to Write comments in C++?

We can write comments in C++ in following ways.
1- Single Line comments
2- Multiline or block comments

Single Line comments

Single line comments are written after two forward slashes // Everything written after these two slashes will be ignored by c++ compiler.
E.g.

//Writes Hello world to output console Screen.

#include "stdafx.h"
#include "iostream"

using namespace std;
void main()
{
     //Writes Hello world to output console Screen.
     cout << "Hello world";
     getchar(); // To hold the output console screen.
}

When above program will rum compiler will consider everything written after // in the same line and will ignore it. as shown below
Output:

Write comments in C++

Multiline or block comments

Multiline comments are written with in /* */.
/* is the starting point of multiline comments and */ is the ending point.
Anything written inside these will be ignored by compiler.
E.g.

/*Writes Hello world
to output
console Screen.*/

#include "stdafx.h"
#include "iostream"

using namespace std;
void main()
{
     /*Writes Hello world
          to output
     console Screen.*/
     cout << "Hello world";
     getchar(); // To hold the output console screen.
}

When this code will run compiler will ignore everything written inside /* */.
Output:
Write comments in C++
Comments are tricky to use like:
// this line of code is commented and is ignored by compiler. //comments inside comments.
The above line of code will not generate any error as everything written after // will be considered as comments.
But what if we write comments like:
/* this is outer
block of comments./*this is the inner block of comments.
*/
outer block of comments will end
here */

the above will generate error and will not let compiler to run program.

Note:-Do not write comments inside comments.

Leave a Reply

Your email address will not be published. Required fields are marked *