Programming C++  «Prev  Next»
Lesson 12 Comment style
Objective Examine the preferred comment style in C++.

C++ Preferred Comment Style

Well-chosen comments make C++ programs easier to understand and maintain. Poorly chosen comments add noise, go out of date, and confuse the next developer. In modern C++, the goal is to combine self-documenting code with a small number of clear, accurate comments.

C++ supports two primary comment styles:

  • Rest-of-line comments that start with //.
  • Block comments that start with /* and end with */.

In practice, the preferred comment style for modern C++ code is the rest-of-line comment using //, with block comments reserved for specific situations such as file-level banners or temporarily disabling larger sections of code.

C++ Comment Syntax

Rest-of-line comments (//)

Everything after // on a line is treated as a comment and ignored by the compiler:

// C++ rest-of-line comment
int count = 0; // Initialize counter

This style is preferred for most comments because it is simple, easy to read, and works well alongside code. You can place the comment on its own line, or after a statement on the same line, as long as it improves readability rather than cluttering the code.

Block comments (/* ... */)

Block comments begin with /* and end with */. The compiler treats everything in between as a comment, even across multiple lines:

/* Block comment in C++
   spanning multiple lines. */

Block comments are convenient for:

  • File or module banners at the top of a source file.
  • Short, multi-line explanations that would be awkward as many // lines.
  • Temporarily commenting out a section of code during debugging (with care).

However, block comments do not nest. If a block comment contains another /* or */, the compiler may see the wrong closing delimiter and report confusing errors. This is one reason why // comments are considered less error-prone and are preferred for everyday use.

Preferred Comment Style in Modern C++

Except for genuinely long, multi-line explanations, the rest-of-line // comment is the preferred style in C++. It is:

  • Easy to insert and remove when refactoring code.
  • Less fragile than block comments, which can accidentally span more lines than intended.
  • Visually aligned with the code it describes, especially when grouped in vertical columns.

Comments themselves should be concise but written in clear, natural language. They should explain why code exists or what contractual behavior it guarantees—not simply restate what each line does.

For example, the following adds little value:

int weight; // weight stores the weight of a person

A better approach is to choose a meaningful name, such as personWeightKg, and reserve comments for domain-specific rules, units, or assumptions that are not obvious from the identifier alone.

Comments and Self-Documenting Code

Modern C++ encourages you to express important ideas directly in code by using:

  • Well-named classes and structs to represent domain concepts.
  • Clear member and free function names that describe behavior.
  • Enums, strong types, and RAII objects instead of “magic values” and global variables.

Whenever your design introduces a meaningful concept—such as an Order, Vector3D, or BankAccount—you should represent it as a type in the code. This makes the code itself carry the design, so readers do not have to reconstruct it from comments or separate documents.

A useful guideline is: “Do not say in comments what can be clearly stated in code.” If a piece of information can be made obvious by better naming, by a small helper function, or by a dedicated type, prefer that over adding a comment that repeats the intent.

Examples of Rest-of-line and Block Comments

Here are two basic examples of the rest-of-line style:

// C++: GCD program (sketch)
int main()
{
    const int maxTrials = 200; // Number of random trials
    // ...
}

And here is a block comment used for a short file header. In practice, keep such headers focused on information that will remain stable over time, such as purpose, author, and high-level notes:

/*
 * File: investment_simulator.cpp
 * Summary: Simulates compound interest over time.
 */

Avoid embedding details that constantly change (exact compiler version, last compile date, etc.) in comments unless your team explicitly benefits from that information.



C++ Programming Language

Function Documentation Comments

For interfaces—public functions, class methods in libraries, or APIs consumed by other parts of the system—documentation comments are useful and often required by team standards. In this course, we use a documentation style similar to “Javadoc” or Doxygen comments:

/**
 * Computes the value of an investment with compound interest.
 *
 * @param initial_balance  Initial value of the investment.
 * @param ratePercent      Interest rate per period, in percent.
 * @param periods          Number of compounding periods.
 * @return                 Balance after the given number of periods.
 */
double future_value(double initial_balance, double ratePercent, int periods)
{
    double factor = 1.0 + ratePercent / 100.0;
    return initial_balance * std::pow(factor, periods);
}

This style documents the contract of the function:

  • What the function is supposed to do.
  • What each parameter represents.
  • What the function returns.

Tools such as Doxygen can scan these comments in C++ source files and generate HTML or other formatted documentation. Even when you do not run a documentation tool, consistent function comments help readers understand your interfaces quickly.

When Documentation Comments Are Not Necessary

Not every function needs a full documentation block. Short, obvious utility functions often speak for themselves:

int max(int x, int y)
{
    if (x > y)
        return x;
    else
        return y;
}

This implementation is clear without additional comments. If you choose to document such a function, the comment should add information that is not already obvious—for example, how the function behaves for equal arguments or how it fits into a larger algorithm.

Whitespace and Layout

Whitespace and indentation work together with comments to make code readable. Use blank lines to separate logical blocks, and align related comments so that the structure of your code is easy to scan. Avoid placing long paragraphs of text inside comments; instead, break them into short lines that are easy to read.

In addition, modern C++ offers language features such as attributes (for example [[nodiscard]]) that encode intent in a way the compiler can enforce. Do not rely on comments alone to express important requirements when the language provides a more robust alternative.

Adding Comments – Exercise

Practice writing effective comments using the rest-of-line style. In the following exercise, you will add comments to an existing program, choosing where they help and where they are unnecessary.

Click the Exercise link below to provide comments to a program using the rest-of-line comment symbol:

Adding Comments – Exercise

Summary

The preferred comment style in C++ is the rest-of-line // comment, used sparingly and in support of clear, self-documenting code. Reserve block comments for specific purposes such as short banners or multi-line notes. Use documentation comments for public interfaces, and let your types, function names, and modern C++ features carry as much meaning as possible directly in the code.


SEMrush Software