C++ Comments

In the previous tutorial you learned how to write your first C++ program. Now, let's learn about C++ comments.

Tip: We are introducing comments early in this tutorial series because, from now on, we will be using them to explain our code.

Comments are hints that we add to our code, making it easier to read and understand.

Comments are completely ignored by C++ compilers.

For example,

#include <iostream>
using namespace std;

int main() {
    // print Hello World to the screen
    cout << "Hello World";

    return 0;
}

Output

Hello World

Here, // print Hello World to the screen is a comment in C++ programming. The C++ compiler ignores everything after the // symbol.

Note: You can ignore the programming concepts and simply focus on the comments. We will revisit these concepts in later tutorials.


Single Line Comments

In C++, a single line comment starts with // symbol. 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

Here, code before // are executed and code after // are ignored by the compiler.

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.


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, instead of removing the error-prone code, we can use comments to disable 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; }

Why use Comments?

We should use comments for the following reasons:

  • Comments make our code readable for future reference.
  • Comments are used for debugging purposes.
  • We can use comments for code collaboration as it helps peer developers to understand our code.

Note: Comments are not and should not be used as a substitute to explain poorly written code. Always try to write clean, understandable code, and then use comments as an addition.

In most cases, always use comments to explain 'why' rather than 'how' and you are good to go.

Next, we will learn about C++ variables, constants and literals.

Did you find this article helpful?