Introduction to C++ | Comments

C++ Comments

In C++, comments are used to explain the code and make it easier for humans to understand. They are ignored by the compiler and do not affect the program's execution. Comments are an essential part of writing clean and maintainable code.

What is a Comment?

A comment is a part of the code that is not executed but is intended to provide explanations or notes for anyone reading the code. It can describe the purpose of the code, clarify complex logic, or remind developers of important considerations.

Types of Comments in C++

C++ supports two types of comments:

Syntax of Comments

The syntax for the two types of comments is as follows:

Syntax of Single-line Comment


        // This is a single-line comment
                    

Syntax of Multi-line Comment


        /* This is a 
           multi-line comment
           that spans multiple lines */
                    

Example of Single-line and Multi-line Comments

Here is an example demonstrating both types of comments:

Code Example


        #include <iostream>
        using namespace std;
        
        int main() {
            int a = 5;  // This is a single-line comment
        
            /* This is a multi-line comment
               explaining the next block of code. */
            int b = 10;
        
            cout << "The sum of a and b is: " << (a + b) << endl;
        
            return 0;
        }
                    

Output

The sum of a and b is: 15

Explanation of Code

In the code above, the first comment explains the variable a, while the multi-line comment provides additional context for the variable b. The comments are ignored by the compiler, so they do not affect the output of the program. The final line of the code prints the sum of a and b.

When to Use Comments

Comments should be used wisely in your code. They can help make your code more understandable for others (or yourself) in the future. Here are some best practices:

Pro Tip:

💡 Pro Tip

When writing comments, aim for clarity and conciseness. Keep your comments relevant and focused on explaining what the code is doing, not how it works (unless it's necessary for understanding). This will improve the readability and maintainability of your code.