Writing Comments
in C++
Learn to write comments that explain intent and invariants, making your code readable, maintainable, and collaborative.
What Are Comments?
Comments are lines in your source code that the compiler completely ignores. They exist solely for humans: your future self, your teammates, and anyone who reads your code months or years later.
Why Comments Matter
Code tells the computer what to do. Comments tell a human why. Without them, even clean code can become a mystery when context is lost.
The Anatomy of a Good Comment
The Golden Rule of Comments
int count = 0; // set count to 0
// Good: explains the invariant
int count = 0; // Tracks unprocessed items; must be < bufferSize
The bad comment adds zero information. The good comment reveals a constraint that isn't visible in the code itself.
Intent vs. Invariants
C++ Comment Syntax
| Feature | // Single-Line | /* Multi-Line */ |
|---|---|---|
| Scope | Until end of line | Until closing */ |
| Nesting | Can appear inside /* */ | Cannot nest /* ... */ blocks |
| Best for | Inline intent notes | Block headers, disabling code |
| Modern convention | Preferred | Use sparingly for docs |
Where to Place Comments
How to Write a Comment
Example: Intent Comment
// elements with equal priority (required by the UI spec).
std::stable_sort(tasks.begin(), tasks.end(), comparePriority);
Example: Invariant Comment
// Invariant: q is non-empty and all elements satisfy
// isValid(). The caller must guarantee this.
while (!q.empty()) {
auto item = q.front();
q.pop();
handle(item); // item.isValid() holds here
}
}
Example: Function Documentation
///
/// Precondition: the range must be sorted in ascending order.
/// Returns: iterator to the element, or 'last' if not found.
///
/// Complexity: \(O(\log n)\) where \(n = \text{last} - \text{first}\).
template<typename It, typename T>
It binarySearch(It first, It last, const T& target);
Decision: Should I Comment?
Common Mistakes
Comment Cheat Sheet
| Situation | Do | Don't |
|---|---|---|
| Simple assignment | State the invariant | Restate the assignment |
| Algorithm choice | Explain why this algorithm | Describe what it does step by step |
| Function signature | Pre/postconditions | Repeat the parameter types |
| Workaround / hack | Link to bug/issue | Leave it unexplained |
| Deleted feature | Delete the code (use Git) | Comment out the block |
Question 1 of 5
Which of the following is the best comment for the line std::sort(v.begin(), v.end());?
Question 2 of 5
What is an invariant comment?
Question 3 of 5
A teammate comments out 40 lines of code "in case we need it later." What should you advise?
Question 4 of 5
You see this comment above a function:
/// Precondition: \(n > 0\)
What type of comment is this?
Question 5 of 5
Which problem is caused by stale comments?