Comments in CPP with Example

Comments in C++ are essential for documenting your code, making it more understandable for both yourself and others who might read or work with your code.

C++ supports two types of comments:

  1. Single-Line Comments:
  2. Single-line comments are used to annotate a single line of code. They start with // and continue until the end of the line. Single-line comments are commonly used for short explanations of code or to disable a line temporarily. For example:

    // This is a single-line comment
    int x = 43; // This comment explains the variable assignment

    Anything which is after // on the same line will be ignored by the c++ compiler.

  3. Multi-Line Comments:
  4. In C++, multi-line comments are enclosed within /* and */ delimiters and can span multiple lines. They are commonly used for longer explanations or for commenting out entire sections of code. For example:

    /* This is a multi-line comment.
       It can span across multiple lines
       and is often used for more detailed explanations. */
    int x = 10; /* You can also use multi-line comments on a single line */

    Anything which is between /* */ will be ignored by the C++ compiler.

Here's an example that demonstrates how comments can be used to describe code:

#include <iostream>

int main() {
    // This is a single-line comment
    int age = 32; // The age of the user

    /* This is a multi-line comment.
       It explains that we are going to print a message. */
    std::cout << "Hello, World!" << std::endl;

    return 0;