English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Comments

In this tutorial, we will learn C ++Comments, why use them, and how to use them with the help of examples.

C ++Comments are code hints and feature descriptions that programmers can add to make their code easier to read and understand. Comments are ignored by C ++compilers completely ignore them.

There are two ways to add comments to code:

// -Single-line comments

/* */ -Multi-line comments

Single-line comments

In C ++in, any line that starts with//are comments. For example,

// Declare a variable
int a;
// with a value2Initialize variable 'a'
a = 2;

Here, we have used two single-line comments:

  • //Declare a variable

  • //with a value2Initialize variable 'a'

We can also use single-line comments like this:

int a;    // Declare a variable

Multi-line comments

In C ++in,/*and*/Any line between them is also a comment. For example,

/* 
   Declare a variable salary 
   Store employee salary
*/
int salary = 2000;

This syntax can be used to write single-line comments and multi-line comments.

Debugging with comments

Comments can also be used to disable code to prevent its execution. For example,

#include <iostream>
using namespace std;
int main() {
   cout << "some code";
   cout << "error code";
   cout << "some other code";
   return 0;
}

If an error occurs during the execution of the program, we can use comments to disable it instead of deleting the code that is easy to go wrong; this is a very useful debugging tool.

#include <iostream>
using namespace std;
int main() {
   cout << "some code";
   // cout << "error code";
   cout << "some other code";
   return 0;
}

Expert Tips:Remember to use the shortcut keys for comments; they are really helpful. For most code editors, it applies to Windows (Ctrl + /) and Mac (Cmd + /)

Why use comments?

If we write comments on the code, we will find it easier to understand the code in the future. Moreover, it will be easier for other developers to understand the project code.

Note:Comments should not replace the method of explaining poorly written code in English. We should always write well-structured and self-explanatory code and then use comments.

As a general rule of thumb, use comments to explainWhyYou did something, not youHowDo something.