Geek Slack

Learn C++
About Lesson


C++ Comments


C++ Comments

Comments in C++ are used to explain and annotate the code, making it easier to understand. Comments are ignored by the compiler and do not affect the execution of the program. There are two types of comments in C++: single-line comments and multi-line comments.

1. Single-Line Comments

Single-line comments start with // and continue until the end of the line. They are typically used for short explanations or notes.

#include <iostream>

int main() {
    // This is a single-line comment
    std::cout << "Hello, World!" << std::endl; // Print a message to the console
    return 0;
}

In the example above, the comments explain what the code is doing. They start with // and continue to the end of the line.

2. Multi-Line Comments

Multi-line comments start with /* and end with */. They can span multiple lines and are useful for longer explanations or block comments.

#include <iostream>

int main() {
    /* This is a multi-line comment
       It spans multiple lines
       and is used for longer explanations */
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

In the example above, the multi-line comment provides a longer explanation and spans multiple lines. It starts with /* and ends with */.

3. Commenting Out Code

Comments can also be used to temporarily disable code without deleting it. This is useful for debugging or testing different parts of the code.

#include <iostream>

int main() {
    int x = 10;
    int y = 20;
    
    // std::cout << "x: " << x << std::endl;
    // std::cout << "y: " << y << std::endl;

    // Uncomment the lines below to print the values of x and y
    // std::cout << "x: " << x << std::endl;
    // std::cout << "y: " << y << std::endl;
    
    return 0;
}

In the example above, the lines that print the values of x and y are commented out. To enable them, simply remove the // at the beginning of each line.

4. Best Practices for Comments

Here are some best practices for writing comments in C++:

  • Keep comments concise and relevant.
  • Use single-line comments for brief notes and multi-line comments for detailed explanations.
  • Update comments if the code changes to ensure they remain accurate.
  • Avoid obvious comments that state what the code does; focus on explaining why it does it.
  • Use comments to explain complex logic or algorithms.

Conclusion

Comments are an essential part of writing readable and maintainable code. By using single-line and multi-line comments effectively, you can make your C++ programs easier to understand for yourself and others. Remember to follow best practices to ensure your comments are helpful and informative.

Join the conversation