C++ Comments
Single-line `//`, multi-line `/* ... */`, and the rules of writing comments your future self will thank you for.
Comments are notes for humans — the compiler ignores them entirely. They explain why, document edge cases, and disable code temporarily.
cpp// Single-line comment — everything after `//` to the end of line. /* Multi-line comment — spans multiple lines until the closing star-slash */
cpp// Above a function, explain what it does int add(int a, int b) { return a + b; // inline comment for non-obvious lines } /* Block comment for whole-file or section explanation * (the leading `*` on each line is just convention). */
Tools like Doxygen parse a special comment style to generate HTML docs:
cpp/** * Adds two integers. * @param a first number * @param b second number * @return the sum */ int add(int a, int b) { return a + b; }
| Bad — explains the what | Good — explains the why |
|---|---|
i++; // increment i | i++; // skip the header row |
if (x > 0) | // guard against the underflow we saw in production on 2024-03-12 |
/* TODO: fix this */ (no context) | // TODO(arav): replace once gateway v2 ships in Q3 |
Comments are great for temporarily disabling code:
cpp// debugLog("entered loop"); runProductionPath();
But don't ship commented-out code — git history is the right place for it.
- Nesting
/* */—/* /* nested */ */is invalid; the first*/closes. Use//for nestable comments. - Outdated comments — code changes, comment doesn't. Worse than no comment.
- Restating obvious code —
i++ // adds 1 to i. Skip it. - Walls of
/* * */— for short comments,//is cleaner. - Missing context in TODO —
// TODOwith no name/date is impossible to action.
- Document a function — Add a Doxygen-style comment to
int max(int, int). Hint:@param,@return. - Toggle code — Comment out a line of code, run, uncomment, run. Hint:
//is fastest. - TODO triage — Pick any open-source repo, search for
TODO— note how few have owners. Hint: lesson learned. - Review your last project — Find one "what" comment and rewrite it as a "why". Hint: explain intent.
💡 Think Like a Programmer: Code reads top-to-bottom; comments explain top-to-side. If your code needs a paragraph to explain it, refactor the code first — the best comment is a clearer name.
Quick recap quiz?
We'll generate 5 MCQs from this lesson and check your understanding instantly. Takes ~30 seconds.
Program
// Calculate the area of a circle.
// Uses M_PI from <cmath> (more precise than the literal 3.14).
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double r = 5.0;
/* Area formula: A = π × r² */
double area = M_PI * r * r;
cout << area << "\n";
return 0;
}