Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Code Comments in C++

Introduction to Code Comments

Code comments are annotations in the source code of a program that are ignored by the compiler. They are used to explain and clarify the code to human readers. Comments can help others, or even yourself, understand the code better when revisiting it after some time.

Types of Comments in C++

In C++, there are two primary types of comments:

  • Single-line comments
  • Multi-line comments

Single-line Comments

Single-line comments start with two forward slashes // and extend to the end of the line. They are typically used for short explanations or notes.

Example:

// This is a single-line comment
int x = 10; // This is also a single-line comment
                

Multi-line Comments

Multi-line comments start with /* and end with */. They can span multiple lines and are useful for longer explanations or for commenting out blocks of code during debugging.

Example:

/* This is a multi-line comment
   It can span multiple lines */
int y = 20; /* This is also a multi-line comment */
                

Best Practices

While comments are helpful, it is important to use them effectively. Here are some best practices:

  • Comment on the intent of the code, not the obvious actions.
  • Keep comments up-to-date with code changes.
  • Avoid redundant comments that state the obvious.
  • Use comments to explain complex logic or algorithms.
  • Use TODO comments to indicate areas for future improvements.

Example:

// Calculate the factorial of a number
int factorial(int n) {
    if (n == 0) {
        return 1; // Base case
    }
    return n * factorial(n - 1); // Recursive case
}
                

Conclusion

Comments are an essential part of writing readable and maintainable code. By following best practices and using comments judiciously, you can make your code more understandable for yourself and others. Remember, the goal of comments is to make the code clearer and easier to work with, not to clutter it with unnecessary information.