C++ Comments
A comment is text the compiler ignores. Comments explain the code to people: why something is done, what a function expects, or a warning for the next person who changes it.
Single-line comments
// starts a comment that runs to the end of the line.
#include <iostream>
int main() {
// Greet the user
std::cout << "Hello\n"; // also ignored
return 0;
}Hello
Multi-line comments
/* starts a comment that ends at */, possibly lines later. Such comments cannot be nested.
#include <iostream>
int main() {
/* This program prints one line.
The second line is switched off. */
std::cout << "Line one\n";
/* std::cout << "Line two\n"; */
return 0;
}Line one
Comments that help
A good comment explains why, not what: the code already says what. Compare:
total = total + 1; // add one to total (not useful)
total = total + 1; // the header row counts as a line too (useful)Functions are often introduced by a short comment saying what they do, what they need and what they return:
// Returns the average of the values; values must not be empty.
double average(const std::vector<double>& values);Many projects write such comments in a fixed style (for example with /// or /** ... */) so that tools like Doxygen can turn them into documentation pages.
Keep comments short and up to date. A comment that no longer matches the code misleads the reader; when you change code, change its comment too. Often the best "comment" is a clear name: int studentCount needs no explanation, int n does.
Switching code off
While testing, it is common to "comment out" a line to see what happens without it. That is fine during work, but delete such lines before you share the code; version control keeps the old versions for you.
Practice exercises
- Add a comment above each line of the Hello World program.
- Switch a line off with
//, run the program, then switch it back on. - Rewrite a comment that only repeats the code so it explains a reason instead.