TExcelTAD
Home › C++ › C++ Comments

C++ Comments

Comments are notes for humans. The compiler throws them away, so they never change what your program does. Good comments explain why code exists or why it was written a certain way — the code itself already shows what it does.

Single-line comments

Two slashes // start a comment that runs to the end of the line. It can stand on its own line or follow code:

cpp · try it yourself
#include <iostream>

int main() {
    // Greet the user
    std::cout << "Welcome!\n";
    std::cout << "Goodbye!\n"; // printed last
}
Welcome!
Goodbye!

Multi-line comments

/* starts a comment that continues until the next */, even across many lines:

cpp · try it yourself
#include <iostream>

int main() {
    /*
       This program prints the size of a pizza order.
       The numbers are hard-coded for now.
    */
    int slices = 8;
    std::cout << "Slices: " << slices /* per pizza */ << "\n";
}
Slices: 8

Note: Block comments cannot be nested. In /* a /* b */ c */ the comment ends at the first */, and c */ becomes a syntax error.

Commenting out code

While debugging, it is handy to disable a line without deleting it. Most editors toggle // on the selected lines with Ctrl+/.

cpp · try it yourself
#include <iostream>

int main() {
    std::cout << "Step 1\n";
    // std::cout << "Step 2\n";   (temporarily disabled)
    std::cout << "Step 3\n";
}
Step 1
Step 3

Documentation comments

Many projects use a special style — /// or /** ... */ — in front of functions and classes. Tools such as Doxygen read them and generate HTML documentation:

cpp
/// Returns the area of a rectangle.
/// @param w width in metres
/// @param h height in metres
double area(double w, double h);

Writing good comments

Avoid Prefer
i = i + 1; // add one to i Explaining intent: // skip the header row
Out-of-date comments that contradict the code Updating comments whenever the code changes
Huge blocks of commented-out code Deleting dead code (version control remembers it)

Test yourself

Which symbol starts a single-line comment?

  1. #
  2. //
  3. --
  4. <!--

Can multi-line /* */ comments be nested?

  1. Yes, to any depth
  2. Yes, but only two levels
  3. No, the first */ ends the comment
  4. Only in C++20