C++ Comments

In this lesson, you will learn about C++ Comments, their objective, and how to utilize them with the aid of practical examples.

C++ Comments Explained

The C++ compiler ignores all of the characters that are present in any comment. Comments are of two types (single and multi-line) and are supported by C++. There are two methods for including code comments:

  • Single-Line Comments
  • Multiple-line comments

1 – Single-Line Comments

Every line in C++ that begins with // is a comment. We have used two one-line comments in this instance:

/ /creating an int a variable;
/ /setting the variable 'a' to have a value of 2;

Additionally, we can use a single-line comment like this:

int variable =3;  //defining a variable with int a

2 – Multi-line Comments

Any line in C++ between /* and */ also functions as a comment. For instance,

/*defining a variable for employee salaries
and number of employees */
int salary = 2000;
int no_of_employees = 50;

The single-line and multi-line comments can both be written using this syntax.

Why are comments used?

Simpler to understand in the future: It will be simpler to understand the code if we add comments to our code.

Easier to understand for other programmers: It will be simpler for other programmers to understand the code.

Useful debugging tool: You can disable code using comments to stop it from running. Instead of eliminating the code prone to errors, we can use comments to prevent it from being executed if we encounter an error while executing the Program.

Rule of thumb

  • Use comments to describe why you did something rather than how you did it as a general rule of thumb.
  • Always write clear, self-explanatory code when writing a program.

This concludes the Syntax of the C++ Comments lesson. In the next lesson, you will learn about the Data Types in C++.