Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 171 ยท Getting Started

Comments

Write clear C++ comments with // and /* */, document functions Doxygen-style, avoid the nesting and backslash traps, and learn which comments help.

A comment is text in your source code that the compiler ignores. Comments are written for people: your teammates, the stranger who inherits your code in three years, and you, next month, when you've forgotten why a line looks the way it does.

C++ has two kinds of comments, plus a widely used convention for documentation comments. The syntax takes two minutes to learn. Knowing what to write in a comment takes longer, so this lesson also covers the habits that separate helpful comments from noise, and two traps that surprise even experienced programmers.

Single-line comments: //

Two slashes start a comment that runs to the end of the line. Everything after // on that line is ignored:

C++ Single-line comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A // comment can sit on its own line, describing the code below it, or at the end of a line of code (an end-of-line comment). The last comment shows another everyday use: putting // in front of a statement comments it out, so it stops running without being deleted. Remove the // and run again to switch it back on.

Single-line comments are the most common kind in modern C++. Most editors comment out the selected lines with Ctrl + / (Cmd + / on macOS).

Multi-line comments: /* */

A comment that starts with /* continues until the next */, even across many lines. This style is inherited from C:

C++ Multi-line comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output is 37 C = 98.6 F and Boiling: 212 F. Notice the last line: because /* */ has a clear end, it can even sit in the middle of a line, here labeling an argument. Some codebases use this to name arguments whose meaning isn't obvious, as in connect(host, /* retries */ 3).

Trap 1: /* */ comments don't nest

The first */ always ends a /* comment, no matter how many /* came before. So if the code you're commenting out already contains a /* */ comment, the outer comment ends too early. This example fails on purpose:

C++ Nested block comments break (on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The comment that began on line 4 ends at the */ of old note. The compiler then sees std::println("two"); as real code, followed by a stray */, and reports error: expected primary-expression before '/' token on line 7. GCC also warns '/*' within comment, which is the real clue.

That's why many teams use // for all ordinary comments: you can always wrap a region in /* */ safely when nothing inside uses that style. Even safer for disabling large blocks of code is the preprocessor, which does nest:

C++
#if 0
    std::println("one");  /* old note */
    std::println("two");
#endif

Everything between #if 0 and #endif is removed before compilation. Still, disabled code shouldn't stay around for long; version control (like Git) remembers old code for you.

Trap 2: a backslash at the end of a // comment

Before comments are removed, the compiler joins any line that ends with a backslash \ to the next line. That's handy for long macros, but it means a // comment ending in \ swallows the following line:

C++ The trailing backslash trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

You might expect 15, but the program prints 10: the line total = total + 5; became part of the comment. GCC warns multi-line comment [-Wcomment], one more reason to always compile with warnings on. Avoid ending a comment with a backslash; add a space and some text, or rephrase.

Comments are not inside strings

Comment markers inside a string literal are just characters. The compiler knows it's inside a string and doesn't look for comments there:

C++ Comment markers in strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Both lines print exactly what's inside the quotes, including the slashes and stars.

Documentation comments (Doxygen style)

Functions, classes and libraries need explanations that go beyond a single line: what each parameter means, what the function returns, what can go wrong. The most widely used convention in C++ is Doxygen style. Doxygen is a free tool that reads specially formatted comments and generates HTML or PDF documentation. Even if you never run the tool, editors like Visual Studio, VS Code and CLion show these comments as tooltips when you hover over a function.

Doxygen comments start with /// or /**, and use commands beginning with @ (or \):

C++ A documented function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The most common commands are:

Command Meaning
@brief A one-sentence summary (Doxygen can also use the first sentence automatically).
@param name Describes one parameter. Write one per parameter, in order.
@return Describes the return value.
@throws Names an exception the function may throw and when.
@note, @warning Extra information or a caution for callers.
@pre, @post Preconditions (what must be true before the call) and postconditions.

You'll also see //! and /*! comments; they're Doxygen variants that work the same way. Pick one style per project and use it consistently. Documentation comments belong mostly in header files, next to the declarations that other people read, which you'll learn about in Header Files and Multiple Source Files.

Tip: Don't let {:>6} in the example distract you. It's a format specification that right-aligns a value in 6 columns, and you'll learn it in Printing Output.

Good commenting habits

Comments that repeat the code add nothing and quickly become wrong when the code changes. Compare:

C++
// Bad: says what the code already says.
i = i + 1;  // add one to i

// Good: says why.
// Skip the header row of the CSV file.
row_index = row_index + 1;

Experienced developers follow a few rules of thumb:

  • Explain why, not what. The code shows what happens. A comment should tell readers why: a business rule, a workaround for a bug, a reason a simpler approach doesn't work.
  • Prefer clear code over comments. If you need a comment to explain what a variable holds, a better name might remove the need. int elapsed_ms beats int t; // elapsed time in milliseconds.
  • Document interfaces. Every function that others call deserves a short description of its parameters, return value and any surprises.
  • Keep comments up to date. A wrong comment is worse than none, because readers trust it. Update or delete comments whenever you change the code they describe.
  • Mark unfinished work consistently. // TODO: and // FIXME: are widely used markers that editors highlight and search tools find. Don't let them pile up forever.
  • Don't keep dead code in comments. Version control remembers deleted code; commented-out blocks just confuse readers.
  • Write comments in clear, simple English (or the language your team agrees on), with full sentences for anything longer than a few words.

Here are comments that earn their place:

C++
// The API returns timestamps in seconds, but our clock uses milliseconds.
long long expires_at = response_time * 1000;

// Binary search requires the list to be sorted; load_scores() guarantees it.
auto position = std::lower_bound(scores.begin(), scores.end(), target);

// TODO: replace the linear scan once we have more than a few hundred users.

Each one tells the reader something the code alone can't: units, assumptions, and plans.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does int x = 1; x = x + 2; // x = x + 3; followed by std::println("{}", x); print?

    Everything after // is ignored, so only x = x + 2 runs and x ends up as 3.
  2. 2. How do you write a comment that ends on the same line it starts?

    // starts a single-line comment in C++. # starts a preprocessor directive, and <!-- --> is HTML.
  3. 3. Why does /* a /* b */ c */ cause a problem?

    Block comments don't nest. The comment ends at the first */, so c */ is seen as code and causes an error.
  4. 4. What does std::println("a // b"); print?

    Inside a string literal, // is just two characters. Comments are only recognized outside strings.
  5. 5. Which comment is the most useful?

    Good comments explain why. The others repeat the code or keep dead code around.

Summary

  • // starts a comment that ends at the end of the line; it's the everyday choice in modern C++.
  • /* ... */ comments can span lines or sit inside a line, but they don't nest: the first */ ends them.
  • Use #if 0 ... #endif to disable a block that might contain comments, and let version control keep old code.
  • A // comment ending in \ swallows the next line; -Wall warns about it.
  • Comment markers inside string literals are plain text.
  • Doxygen comments (/// or /** */ with @brief, @param, @return) document functions and show up in editor tooltips.
  • Comment the why, prefer clear names over explanations, and keep comments in sync with the code.

Next: Printing Output, where you'll master std::println, format strings, std::cout and escape sequences.