C++ Comments: In this tutorial, we will find out about C++ comments, why we use them, and how to use them with the help of examples.

C++ comments are clues that a developer can add to make their code simpler to peruse and comprehend. They are totally overlooked by C++ compilers.

There are two different ways to add comments to code:

// – Single Line Comments

/* */ -Multi-line Comments


Single-Line Comments


In C++, any line that starts with // is a comment. For example,

// declaring a variable
int a;

// initializing the variable 'a' with the value 2
a = 2;

Here, we have used two single-line comments:

// declaring a variable
// initializing the variable 'a' with the value 2

We can also use single line comment like this:

int a;    // declaring a variable

Multi-line comments


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

/* declaring a variable
to store salary to employees
*/
int salary = 2000;

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


Using Comments for Debugging

Comments can also be used to disable code to prevent it from being executed. For example,

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

   return 0;
}

If we get an error while running the program, rather than evacuating the error-prone code, we can use comments to debilitate it from being executed; this can be a valuable debugging tool.

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

   return 0;
}

Pro Tip: Remember the shortcut for using comments; it can be really helpful. For most code editors, it’s Ctrl + / for Windows and Cmd + / for Mac.


Why use Comments?

If we write comments on our code, it will be simpler for us to comprehend the code later on. Additionally, it will be simpler for your kindred designers to comprehend the code.

Note: Comments shouldn’t be the substitute for an approach to clarify ineffectively written code in English. We should always write well-structured and self-explanatory code. And, then use comments.

When in doubt of thumb, use comments to clarify Why you accomplished some different options from How you accomplished something, and you are good.


Please feel free to give your comment if you face any difficulty here.


0 Comments

Leave a Reply

Avatar placeholder