Skip to main content

C++ Comments

Introduction

Comments are non-executable text added to the source code that the compiler ignores during compilation. They serve as notes for developers to explain the code's purpose, functionality, or any important considerations. Well-commented code is easier to understand, maintain, and debug, making comments an essential aspect of good programming practice.

In this tutorial, you'll learn:

  • What comments are and why they are important
  • Different types of comments in C++
  • Best practices for writing effective comments
  • Real-world examples of comment usage

Types of Comments in C++

C++ supports two types of comments:

  1. Single-line comments - Starting with // and continuing until the end of the line
  2. Multi-line comments - Enclosed between /* and */, can span multiple lines

Let's explore each type with examples.

Single-Line Comments

Single-line comments begin with two forward slashes (//) and continue until the end of the line. These are ideal for brief explanations or annotations.

cpp
#include <iostream>

int main() {
// This is a single-line comment
std::cout << "Hello, World!" << std::endl; // Prints Hello, World!

int sum = 10 + 5; // Adding two numbers

return 0; // Program completed successfully
}

Multi-Line Comments

Multi-line comments start with /* and end with */. Everything between these markers is treated as a comment, regardless of how many lines it spans. These are useful for longer explanations, function documentation, or temporarily disabling blocks of code.

cpp
#include <iostream>

/*
* This is a multi-line comment.
* It can span several lines.
* Often used for function descriptions or
* to provide detailed explanations.
*/
int main() {
std::cout << "Multi-line comments example" << std::endl;

/*
This code is commented out and won't execute
int x = 10;
int y = 20;
std::cout << x + y << std::endl;
*/

return 0;
}

Practical Applications of Comments

1. Code Documentation

One of the primary uses of comments is to document your code. This includes explaining:

  • What a function does
  • Parameters and return values
  • Pre-conditions and post-conditions
  • Algorithm explanations
cpp
/**
* Calculates the factorial of a non-negative integer.
*
* @param n A non-negative integer
* @return The factorial of n (n!)
* @note Time complexity: O(n)
*/
unsigned long long factorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n <= 1) {
return 1;
}

// Recursive case: n! = n * (n-1)!
return n * factorial(n - 1);
}

2. Code Organization

Comments can help organize your code into logical sections, making it easier to navigate.

cpp
#include <iostream>
#include <string>
#include <vector>

int main() {
//----------------------
// Variable declarations
//----------------------
std::string userName;
int userAge;
std::vector<int> scores;

//----------------------
// User input section
//----------------------
std::cout << "Enter your name: ";
std::getline(std::cin, userName);

std::cout << "Enter your age: ";
std::cin >> userAge;

//----------------------
// Processing section
//----------------------
// Process user data...

//----------------------
// Output section
//----------------------
std::cout << "Thank you, " << userName << "!" << std::endl;

return 0;
}

3. Debugging Aid

Comments can be used to temporarily disable code during debugging without deleting it.

cpp
#include <iostream>

int main() {
int total = 0;

// Add values from 1 to 5
for (int i = 1; i <= 5; i++) {
total += i;

// Debug information
std::cout << "After adding " << i << ", total is " << total << std::endl;
}

/*
// This alternative calculation is commented out for now
total = 5 * 6 / 2;
std::cout << "Alternative calculation: " << total << std::endl;
*/

return 0;
}

Output:

After adding 1, total is 1
After adding 2, total is 3
After adding 3, total is 6
After adding 4, total is 10
After adding 5, total is 15

4. TODO Comments

Comments can also be used to mark areas of the code that need future attention. Many IDEs recognize special comment tags like TODO, FIXME, or NOTE.

cpp
#include <iostream>
#include <string>

void processUserData(const std::string& userData) {
// TODO: Implement input validation

// FIXME: The function crashes with empty strings

// NOTE: This function will need updating when we switch to the new API

std::cout << "Processing: " << userData << std::endl;
}

int main() {
processUserData("sample data");
return 0;
}

Best Practices for Comments

  1. Be concise and clear:

    • Write comments that add value and explain "why" rather than "what"
    • Avoid obvious comments that simply restate what the code is doing
  2. Keep comments up-to-date:

    • Update comments when you change the code
    • Outdated comments are worse than no comments at all
  3. Use consistent style:

    • Adopt a consistent commenting style throughout your project
    • Follow your team or organization's commenting guidelines
  4. Don't comment bad code, rewrite it:

    • If code requires extensive comments to understand, consider refactoring it
    • Good code should be largely self-documenting
  5. Use comments for complex logic:

    • Focus comments on explaining complex algorithms or business rules
    • Document non-obvious behavior or edge cases

Advanced Example: Documentation Comments

In larger projects, it's common to use specialized comment formats that can be processed by documentation generators like Doxygen. Here's an example:

cpp
#include <vector>
#include <string>

/**
* @brief A student record class
*
* This class represents a student in an educational system
* and manages all associated data.
*
* @author Your Name
* @date 2023-07-01
*/
class Student {
private:
std::string name;
int id;
std::vector<int> grades;

public:
/**
* @brief Default constructor
*/
Student();

/**
* @brief Parameterized constructor
* @param studentName The name of the student
* @param studentId The unique ID for the student
*/
Student(const std::string& studentName, int studentId);

/**
* @brief Add a new grade for the student
* @param grade The grade to add (0-100)
* @return true if the grade was added successfully, false otherwise
* @throws std::invalid_argument if grade is not in range 0-100
*/
bool addGrade(int grade);

/**
* @brief Calculate the student's GPA
* @return The grade point average (0.0-4.0)
*/
double calculateGPA() const;
};

Summary

Comments are a vital part of writing maintainable, readable code in C++. They help document your code's functionality, explain complex logic, aid in debugging, and organize your code into logical sections. By following best practices for comments, you can create code that is easier for others (and your future self) to understand and modify.

Remember:

  • Use single-line comments (//) for brief explanations
  • Use multi-line comments (/* */) for longer documentation
  • Write meaningful comments that explain "why" rather than just "what"
  • Keep comments updated when you change code
  • Don't use comments as a substitute for writing clean, self-documenting code

Exercises

  1. Add appropriate comments to this function that calculates the Fibonacci sequence:

    cpp
    int fibonacci(int n) {
    if (n <= 1) return n;
    return fibonacci(n-1) + fibonacci(n-2);
    }
  2. Identify and fix the poor commenting practices in this code snippet:

    cpp
    // This function adds x and y
    int add(int x, int y) {
    // Add x and y
    int result = x + y;
    // Return the result
    return result;
    }
  3. Write a well-commented C++ program that reads a text file and counts the number of words in it.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)