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:
#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:
#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*/, andc */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+/.
#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:
/// 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?
- #
- //
- --
- <!--
Can multi-line /* */ comments be nested?
- Yes, to any depth
- Yes, but only two levels
- No, the first
*/ends the comment - Only in C++20