Topic 5: Comments

Comments in C++ are ignored by the compiler but are useful for programmers. They are used to annotate code for future reference and can be used to make certain lines of code inactive during testing.

In C++, comments can be written in two ways:

  • /* comment */: This is a multi-line comment.
  • // comment: This is a single-line comment.

Comment characters (/*, */, and //) have no special meaning within a character constant, a string literal, or another comment.

Why Use Comments?
  • Documentation: Helps in understanding the code when revisited after a long time.
  • Debugging: Useful in temporarily disabling code.
  • Collaboration: Helps other programmers understand your code.
Example 1: Single Line Comment
// declaring a variable
int a;

// initializing the variable 'a' with the value 2
a = 2;
Example 2: Multi-line Comment
/* declaring a variable
to store salary for employees */
int salary = 2000;
Example 3: Comments within Code Blocks
int main() {
    // This is the main function
    /* Initialize variables */
    int x = 10;
    int y = 20;

    // Print the sum of x and y
    cout << "Sum: " << (x + y) << endl;

    return 0;
}
Example 4: Commenting Out Code
int main() {
    int result = 0;
    // result = 10 + 20; // This line is commented out for testing purposes

    // Uncomment the line below to perform the addition
    // result = 10 + 20;

    cout << "Result: " << result << endl;
    return 0;
}
Best Practices for Using Comments
  • Keep Comments Up-to-Date: Ensure comments reflect the current state of the code.
  • Be Clear and Concise: Write comments that are easy to understand.
  • Avoid Redundancy: Do not comment obvious code.
  • Use Comments for Explanation: Explain why something is done, not just what is done.
Example 5: Avoiding Redundant Comments
// BAD: Redundant comment
int x = 10; // Declare x and initialize to 10

// GOOD: Explain why the value is assigned
int x = 10; // Initializing x to 10 to use as a counter