Comments in C/C++

By | August 15, 2020

A comment is text that the compiler ignores but that is useful for programmers. Comments are normally used to annotate code for future reference. Comments are statements that are not executed by the compiler and interpreter. The compiler treats them as white space.

  • It makes a program more readable and error finding become easier.
  • One important part of good documentation is Comments.
  • All programming languages allow for some form of comments.
  • Comments are used to give insight into the design or method of a program. These explain the purpose and functionality of code.
  • Using these comments inside the code, we can place of copyright/licenses, project notes, special thanks, contributor credits, etc. directly in the source code.
  • We can disable the code (or any line of code) using these Comment marker. This is according to property of comment and is called “comment out” of the code.

There are two types of comments in C++ : Single line comment, and Multi-line comment.

1. Single line Comment

These denote single line comment using by // double forward slash

// single line comment 

2. Multi line Comment

These denote multi line comment using by /* … */ (slash, asterisk)

/* This is multi line comment 
in a CPP program to describe some comment by developer  
/* This is 
mult line comment */
#include <iostream>
using namespace std;

// this is single line comment
main() {
   cout << "Hello World"; // this is also a single line comment
   
   /* this is another 
    multi line comment */
   return 0;
}

Note –

  1. Normally, we use // for short comments, and /* */ for longer. But, it is up to you which you want to use.
  2. Comments using the first syntax, therefore, cannot be nested.
  3. They must be maintained to reflect any changes in the code
  4. Excessive comments tend to make the code less readable



Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.