C++ Comments
A comment in C++ is text in your source code that the compiler completely ignores. Comments let you explain what your code does, leave notes for other programmers (or your future self), and temporarily disable lines of code while debugging. They have zero effect on the compiled program — no runtime cost, no output, nothing. Mastering comments is a small skill, but using them well is one of the biggest differences between code that is easy to maintain and code that isn’t.
Overview / How Comments Work
C++ supports two kinds of comments: single-line comments using // and multi-line comments using /* */. Anything after // on a line is ignored until the end of that line. Anything between /* and the next */ is ignored, no matter how many lines it spans.
Comments are removed very early in the build process, during what the C++ standard calls translation phase 3 — before the compiler even looks at keywords, variables, or types. Each comment is conceptually replaced by a single space character. This matters for two practical reasons:
- Comments cannot affect program behavior in any way — they are gone long before code generation happens.
- Because a comment is replaced by whitespace, you can safely place a
/* comment */in the middle of a line, even inside an expression, as long as it doesn’t split a token (like a variable name) in half.
A subtlety many beginners hit: /* */ comments do not nest. The first */ the compiler sees closes the comment, even if you intended it to close an inner one. We’ll see exactly what goes wrong in the Common Mistakes section below.
C++ also has a semi-official convention for documentation comments, written as /** ... */ and processed by tools like Doxygen to auto-generate API documentation. To the compiler, a /** comment is just an ordinary multi-line comment — the extra asterisk has no special meaning to C++ itself, it’s purely a convention that documentation-generating tools look for.
Syntax
// This is a single-line comment
/* This is a
multi-line comment
that can span several lines */
int x = 5; // a comment can also follow code on the same line
int y = /* or sit inline */ 10;
| Form | Scope | Typical use |
|---|---|---|
// text |
From // to the end of the current line |
Quick notes, end-of-line explanations |
/* text */ |
Everything between /* and the matching */, across any number of lines |
Longer explanations, temporarily disabling blocks of code |
/** text */ |
Same as /* */ to the compiler |
Documentation comments read by tools like Doxygen |
Examples
Example 1: Basic single-line and multi-line comments
#include <iostream>
using namespace std;
int main() {
// Declare the width and height of a rectangle
int width = 10;
int height = 5;
/* Calculate the area by multiplying
width and height together */
int area = width * height;
cout << "Area: " << area << endl; // print the result
return 0;
}
Output:
Area: 50
Here the // comments give a quick, one-line explanation right where the relevant code is, while the /* */ comment spans two lines to describe the calculation. If you removed every comment from this program, it would compile and run identically — comments are purely for the humans reading the code.
Example 2: Using comments to disable code while debugging
#include <iostream>
using namespace std;
int main() {
int score = 72;
// int bonus = 10; // bonus feature disabled while testing
int total = score; // + bonus;
cout << "Total score: " << total << endl;
return 0;
}
Output:
Total score: 72
A very common real-world use of comments is "commenting out" code you don’t want to run right now but don’t want to delete either — maybe you’re isolating a bug, or a feature is half-finished. Here the bonus variable and its use are both disabled with //, so the program compiles and runs without them. This is a useful debugging technique, but as you’ll see in Best Practices, it should be temporary, not permanent.
Example 3: Documentation-style comments for a function
#include <iostream>
using namespace std;
/**
* Calculates the average of three integers.
* @param a first value
* @param b second value
* @param c third value
* @return the average as a double
*/
double average(int a, int b, int c) {
return (a + b + c) / 3.0;
}
int main() {
double result = average(4, 8, 15);
cout << "Average: " << result << endl;
return 0;
}
Output:
Average: 9
This example uses the /** ... */ documentation style above the average function. To the compiler this is just an ordinary comment, but tools like Doxygen can scan source files for this pattern and automatically generate reference documentation listing each function’s parameters and return value. This convention is especially valuable on any function whose purpose isn’t obvious from its name and signature alone.
Under the Hood: How the Compiler Handles Comments
When you build a C++ program, the source text passes through several translation phases before machine code is produced. Comment removal happens very early:
- The compiler reads the raw source file as a sequence of characters.
- It scans for the character sequences
//and/*. When it finds//, everything up to (but not including) the next newline is discarded. When it finds/*, everything up to and including the very next*/is discarded. - Each discarded comment is replaced with a single space, which is why a comment can safely separate two tokens without accidentally joining them together (for example,
int/*comment*/x;is treated the same asint x;). - Only after this cleanup does the compiler tokenize the remaining text into keywords, identifiers, operators, and literals, and proceed with parsing and code generation.
Because this happens before parsing, comments cannot be conditionally included, cannot contain preprocessor directives that get evaluated, and have absolutely no effect on the compiled binary’s size or behavior beyond the source text they remove.
Common Mistakes
Mistake 1: Trying to nest /* */ comments
Programmers coming from languages that support nested comments often try this, expecting the whole block to be one comment:
/* This is the outer comment
/* This is meant to be a nested comment */
This part is now outside any comment and breaks the code!
*/
int main() {
return 0;
}
This does not compile. The first */ (after "nested comment") closes the outer comment, not an inner one, because /* */ comments are not nestable. Everything after that — including the line of plain English text and the stray trailing */ — is now treated as actual C++ source code, which the compiler cannot parse.
The fix is to never rely on nesting /* */. If you need to comment out a block that already contains /* */ comments, use // on each line instead, or a preprocessor directive like #if 0 ... #endif:
// This is the outer comment
// This is meant to be a nested comment
// (use // on each line instead of nesting /* */)
int main() {
return 0;
}
Mistake 2: Forgetting to close a multi-line comment
A missing */ silently swallows everything after it — including code you meant to keep — until the compiler finds the next */ anywhere in the file, or reaches the end of the file and reports an error:
#include <iostream>
using namespace std;
int main() {
cout << "Starting program" << endl;
/* TODO: fix this later
cout << "This will never print" << endl;
return 0;
}
Here the opening /* is never closed, so it consumes the rest of the file — including the closing brace of main — and the compiler reports an unterminated comment error instead of compiling. The fix is simply to close every multi-line comment you open:
#include <iostream>
using namespace std;
int main() {
cout << "Starting program" << endl;
/* TODO: fix this later */
cout << "This prints now that the comment is closed" << endl;
return 0;
}
Output:
Starting program
This prints now that the comment is closed
Best Practices
- Comment the why, not the what. Code already shows what it does; a good comment explains a reason, a constraint, or a non-obvious decision.
- Keep comments up to date. A comment that no longer matches the code below it is worse than no comment at all, because it actively misleads readers.
- Avoid leaving large blocks of commented-out dead code in a finished codebase; delete it and rely on version control (like Git) to recover it if needed.
- Use a consistent marker like
// TODO:or// FIXME:for known issues so they’re easy to search for later. - Use
/** ... */documentation comments above public functions and classes so tools and IDEs can show helpful summaries to other programmers. - Prefer several short
//comments over one giant/* */block when annotating individual lines — it’s easier to edit and less error-prone. - Never nest
/* */comments; use//line comments or#if 0 ... #endifwhen you need to disable a block that already contains comments.
Practice Exercises
- Write a program that declares two integer variables and prints their sum. Add a single-line comment above each variable declaration explaining its purpose, and a multi-line comment above the addition explaining the calculation.
- Take a working program of your choice and use
//to comment out one line so the program still compiles but skips that line’s effect. Run it and confirm the output changed as expected. - Write a short function (for example, one that converts Celsius to Fahrenheit) and document it with a
/** ... */comment block that describes its parameter and return value, following the style shown in Example 3.
Summary
- C++ has two comment forms:
//for single-line comments and/* */for multi-line comments. - Comments are stripped out during an early translation phase, before parsing — they have no effect on the compiled program.
/* */comments do not nest; the first*/found always closes the comment, which can turn following text into broken code.- Forgetting to close a
/* */comment silently swallows the rest of the file until the next*/, often producing a compile error. /** ... */is a documentation-comment convention (used by tools like Doxygen) but is otherwise a plain comment to the compiler.- Good comments explain why code exists, not what it obviously does, and should be kept accurate as code changes.
