01 / 20
//

Writing Comments
in C++

Learn to write comments that explain intent and invariants, making your code readable, maintainable, and collaborative.

C++

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.

// Single-Line
Everything after // on that line is a comment. Most common in C++.
/* */ Multi-Line
Everything between /* and */ is a comment, spanning any number of lines.

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.

1
Preserve intent: Explain the reasoning behind a design choice so it isn't accidentally undone.
2
Document invariants: State the conditions that must always be true at a given point in the code.
3
Accelerate onboarding: New team members can understand your code without tracing every line.

The Anatomy of a Good Comment

Good Comment Explains WHY Intent / Purpose States RULES Invariants / Contracts Gives CONTEXT Edge cases / Links Clarifies HOW Non-obvious logic

The Golden Rule of Comments

// Bad: restates the code
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

Intent Comments
Explain why a decision was made. "We use a binary search here because the array is always sorted by the caller."
Invariant Comments
State what must always be true at a specific point. "At this line, the mutex is held and data.size() > 0."

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

1
File header: Describe the module's purpose, author, and any high-level invariants for the entire file.
2
Function header: State preconditions, postconditions, and the function's intent. Use /// or /** for documentation tools.
3
Above tricky logic: Before a non-obvious algorithm or workaround, explain why this approach was chosen.
4
Inline at key points: After a line, mark invariants ("// mutex held here") or edge-case notes.

How to Write a Comment

1
Read the code. Understand what the block does before writing anything.
2
Ask "Would a teammate understand why?" If not, you need a comment.
3
State the intent or invariant in one sentence. Be concise: if it takes a paragraph, refactor the code first.
4
Place it on the line above (or inline for short invariants). Keep it close to what it describes.
5
Update it when the code changes. A stale comment is worse than no comment.

Example: Intent Comment

// Use a stable sort to preserve the original order of
// elements with equal priority (required by the UI spec).
std::stable_sort(tasks.begin(), tasks.end(), comparePriority);

Example: Invariant Comment

void processQueue(Queue& q) {
  // 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

/// Searches for 'target' in the sorted range [first, last).
///
/// 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?

I wrote some code Is the WHY obvious from the code? Yes No comment needed No Can you rename / refactor to clarify? Yes Refactor first No Write a comment (intent or invariant)

Common Mistakes

Restating the Code
i++; // increment i adds nothing. Comment the reason you increment, not the operation.
Stale Comments
Updating code without updating its comment creates lies in your codebase. Treat comments as part of the change.
Commenting Out Code
Use version control (Git) to preserve old code. Commented-out blocks create clutter and confusion.

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?