</>
Skip to content
C++ lessons (6/42)

C++ — Comments

Single-line comments

Use // for a comment on one line:

#include <iostream>
using namespace std;

int main() {
    int x = 10; // This is an assignment
    cout << x << endl; // Print the value
    return 0;
}

Single-line comments are the most common form. Use them to explain why a line exists.

Multi-line comments

Wrap longer comments between /* and */:

#include <iostream>
using namespace std;

int main() {
    /*
      This block explains the algorithm
      we are about to implement. Multi-line
      comments are useful for longer notes.
    */
    int result = 42;
    cout << result << endl;
    return 0;
}

Multi-line comments are not nested:

/*
  Valid comment
  /* Invalid nested comment — compiler error */
*/

Documentation comments

C++ uses Doxygen-style comments:

/**
 * @brief Calculate the sum of two integers.
 * @param a First operand.
 * @param b Second operand.
 * @return The sum of a and b.
 */
int add(int a, int b) {
    return a + b;
}

/// @brief A shorter documentation style
/// @param x The input value
/// @return The squared value
int square(int x) {
    return x * x;
}

When to comment

#include <iostream>
using namespace std;

// GOOD: Explain WHY, not WHAT
int mask = value & 0xFF;  // Extract low byte for legacy compatibility

// GOOD: Mark TODOs and FIXMEs
// TODO: Replace with smart pointers after sprint 3
// FIXME: This breaks when input is negative

// BAD: Redundant comment
int count = 0; // Initialize count to 0

// GOOD: Explain complex logic
double avg = static_cast<double>(sum) / count; // Cast to avoid integer division

Best practices

  • Keep comments near the code they explain
  • Update comments when code changes
  • Use TODO/FIXME markers for searchable notes
  • Don't comment obvious code
  • Use Doxygen for public APIs

Mini Practice

Write C++ code that:

  1. Uses // comments to explain variable declarations
  2. Uses /* */ to write a multi-line description
  3. Documents a function with Doxygen-style comments
  4. Comments out a line of code and explains why

Up Next

In the next lesson, you'll learn about Variables — declaring and using variables in C++.

Related Topics

Frequently Asked Questions about Comments

What is Comments in C++?

Comments is a fundamental concept in C++. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Comments?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Comments.

Why is Comments important in C++?

Comments is essential for C++ development. Understanding this concept will help you write better code and solve real-world problems more effectively.