C++ Comments

Documenting and explaining your code effectively

πŸ’¬ C++ Comments

Comments are text notes in your code that explain what the program does. They're ignored by the compiler but help programmers understand and maintain code effectively.


// This is a single-line comment
#include <iostream>
using namespace std;

int main() {
    cout << "Comments help explain code!" << endl;
    return 0;  // Program ends here
}
                                    

Output:

Comments help explain code!

Types of Comments

//

Single-Line

Comments that span one line only

// This is a comment
/* */

Multi-Line

Comments that span multiple lines

/* This is a
   multi-line comment */
πŸ“

Inline

Comments at the end of code lines

int x = 5; // Store value
πŸ“‹

Documentation

Comments that explain program purpose

// Program: Calculator
// Author: John Doe

πŸ”Ή Single-Line Comments

Single-line comments in C++ start with // and are ideal for brief, inline explanations. They help clarify complex logic, describe variable purposes, or temporarily disable code during debugging. For example, // Calculate total price or // User authentication check improves code readability. These comments are ignored by the compiler, so they don’t affect program execution. Proper use of single-line comments enhances maintainability, making it easier for other developers to understand and modify the codebase efficiently.

#include <iostream>
using namespace std;

int main() {
    // This program demonstrates single-line comments
    
    // Declare variables
    int age = 25;
    string name = "Alice";
    
    // Display user information
    cout << "Name: " << name << endl;  // Print the name
    cout << "Age: " << age << endl;    // Print the age
    
    // Calculate age in days (approximate)
    int daysOld = age * 365;
    cout << "Days old: " << daysOld << endl;
    
    return 0;  // End program successfully
}

Output:

Name: Alice
Age: 25
Days old: 9125

πŸ”Ή Multi-Line Comments

Multi-line comments in C++, enclosed within /* */, provide detailed documentation for code sections, functions, or algorithms. They are perfect for explaining complex logic, summarizing block purposes, or outlining steps in a process. For instance, describing a sorting algorithm or detailing input/output expectations. Unlike single-line comments, they can span multiple lines, offering comprehensive explanations without cluttering the code. This practice improves collaboration and long-term code maintenance, ensuring clarity for future updates or debugging sessions.

/*
 * Program: Simple Calculator
 * Author: Student Name
 * Date: January 2024
 * Purpose: This program performs basic arithmetic
 *          operations like addition and subtraction
 */

#include <iostream>
using namespace std;

int main() {
    /*
       This section declares variables
       for our calculator program
    */
    int num1 = 10;
    int num2 = 5;
    
    /* Perform calculations */
    int sum = num1 + num2;        // Addition
    int difference = num1 - num2; // Subtraction
    
    /*
       Display results to the user
       with clear labels
    */
    cout << "First number: " << num1 << endl;
    cout << "Second number: " << num2 << endl;
    cout << "Sum: " << sum << endl;
    cout << "Difference: " << difference << endl;
    
    return 0;
}

Output:

First number: 10
Second number: 5
Sum: 15
Difference: 5

πŸ”Ή Good Commenting Practices

Effective commenting involves clarity, relevance, and consistency to enhance code understanding and teamwork. Comments should explain why code exists, not just what it doesβ€”for instance, noting business logic behind a calculation. Avoid redundant statements like repeating obvious code actions. Use consistent formatting and update comments with code changes. For example, documenting that a room area calculation (e.g., 12Γ—10 feet = 120 sq ft) meets accessibility standards. Good comments act as a guide, speeding up debugging and onboarding for new developers.

#include <iostream>
using namespace std;

// Function to calculate area of a rectangle
int calculateArea(int length, int width) {
    return length * width;  // Formula: length Γ— width
}

int main() {
    // Get room dimensions
    int roomLength = 12;  // Length in feet
    int roomWidth = 10;   // Width in feet
    
    // Calculate room area
    int area = calculateArea(roomLength, roomWidth);
    
    // Display result with units
    cout << "Room dimensions: " << roomLength << " x " << roomWidth << " feet" << endl;
    cout << "Room area: " << area << " square feet" << endl;
    
    // Check if room is large enough for furniture
    if (area >= 100) {
        cout << "Room is spacious!" << endl;
    } else {
        cout << "Room is cozy." << endl;
    }
    
    return 0;
}

Output:

Room dimensions: 12 x 10 feet
Room area: 120 square feet
Room is spacious!

πŸ”Ή Commenting for Debugging

Comments are invaluable for debugging by allowing temporary code deactivation without deletion. By commenting out suspicious lines, you can isolate issues and test alternatives, such as disabling a function call to check its impact. For example, if a student score system malfunctions, commenting out grade logic helps verify raw input (e.g., score: 85). This non-destructive approach preserves original code, facilitates incremental testing, and can include notes like // TODO: Fix edge case for tracking unresolved bugs efficiently.

#include <iostream>
using namespace std;

int main() {
    int score = 85;
    
    cout << "Student score: " << score << endl;
    
    // Temporarily disabled - testing different grade ranges
    /*
    if (score >= 90) {
        cout << "Grade: A" << endl;
    } else if (score >= 80) {
        cout << "Grade: B" << endl;
    }
    */
    
    // New grading system being tested
    if (score >= 85) {
        cout << "Grade: Excellent" << endl;
    } else if (score >= 70) {
        cout << "Grade: Good" << endl;
    } else {
        cout << "Grade: Needs Improvement" << endl;
    }
    
    // TODO: Add letter grade conversion later
    // FIXME: Handle negative scores
    
    return 0;
}

Output:

Student score: 85
Grade: Excellent

πŸ”Ή Comment Best Practices

Follow these guidelines for impactful commenting: prioritize clarity, keep comments updated, and integrate them into development workflows. Write in plain language, avoid jargon, and explain complex algorithms or business rules. Use tools like Doxygen for automated documentation and include examples where helpful. Comments should complement clean code, not compensate for poor structure. Regularly review comments during code reviews to ensure accuracy. This disciplined approach reduces technical debt and fosters a collaborative, efficient programming environment.

Do's and Don'ts:

  • βœ… DO: Explain WHY you're doing something
  • βœ… DO: Document complex algorithms
  • βœ… DO: Add author and date information
  • βœ… DO: Use TODO and FIXME for reminders
  • ❌ DON'T: State the obvious: x = 5; // Set x to 5
  • ❌ DON'T: Write misleading comments
  • ❌ DON'T: Leave old, outdated comments

πŸ”Έ Good vs Bad Comments:

// ❌ BAD: States the obvious
int age = 25;  // Set age to 25

// βœ… GOOD: Explains the purpose
int age = 25;  // User's age for eligibility check

// ❌ BAD: Doesn't add value
x++;  // Increment x

// βœ… GOOD: Explains why
x++;  // Move to next array position

🧠 Test Your Knowledge

Which symbol starts a single-line comment in C++?