Topic 6 of 91 1. Introduction to C++ Interactive Tutorial

C++ Comments Guide: Single-Line, Multi-Line, and Documentation Styles

10 mins read Last updated: 26 Sep 2026 16,700 views

Direct Answer & Core Concept

Comments are an important part of writing readable C++ code. They allow developers to explain what code does, leave notes for future changes, document functions, and make large programs easier to understand.

C++ provides two built-in comment styles:

  • Single-line comments using //

  • Multi-line comments using /* ... */

C++ developers also commonly use structured documentation comments with tools such as Doxygen to generate API documentation.

In this guide, you will learn how C++ comments work, when to use each type, how documentation comments are written, common mistakes, and practical commenting best practices.

Detailed Explanation & Mechanics

18. If it is, the function returns

true. Otherwise, it returns false. The function is used to determine whether the user can register for the service. */boolisAdult(intage){returnage>=18;}

A concise explanation may be enough:

main.cpp
Run Online
// Returns true when the user meets the minimum age requirement.
bool isAdult(int age) {
    return age >= 18;
}

For a public API, structured documentation can be appropriate:

main.cpp
Run Online
/**
 * Checks whether a user meets the minimum age requirement.
 *
 * @param age User's age.
 * @return true if the user is at least 18; otherwise false.
 */
bool isAdult(int age) {
    return age >= 18;
}

TODO Comments

Developers sometimes use comments to mark unfinished work.

Example:

main.cpp
Run Online
// TODO: Add input validation.

Another example:

main.cpp
Run Online
// TODO: Replace this temporary implementation.

TODO comments can be useful during development, especially when an IDE or code-review system can track them.

However, unfinished TODOs should be reviewed regularly.


FIXME Comments

FIXME is another commonly used convention.

main.cpp
Run Online
// FIXME: Handle invalid input correctly.

It signals that something needs correction.

Other project-specific markers may include:

main.cpp
Run Online
// NOTE: This function is intentionally synchronous.
// HACK: Required for compatibility with the legacy API.
// WARNING: Changing this value affects existing users.

These are conventions rather than special C++ language features.


Comments and Preprocessor Directives

C++ source code often contains preprocessor directives such as:

Comments can be placed around them:

main.cpp
Run Online
// Standard input/output functionality
#include <iostream>

You can also comment out a preprocessor directive:

main.cpp
Run Online
// #include <some-library.h>

The compiler will no longer process that line as an active directive.


Nested Multi-Line Comments

A common beginner mistake is trying to nest block comments.

For example:

main.cpp
Run Online
/*
    Outer comment

    /*
        Inner comment
    */

    More text
*/

C++ block comments do not nest in the way beginners often expect.

This can cause confusing compilation errors because the first */ ends the comment.

If you need to temporarily disable a section that already contains block comments, using // on each line or an editor's comment toggle is often safer.


Comments Inside Strings Are Not Comments

Consider:

main.cpp
Run Online
std::cout << "// This is not a comment";

The text:

is inside a string literal.

It is printed as normal text.

Similarly:

main.cpp
Run Online
std::cout << "/* Not a comment */";

prints:

The compiler recognizes the comment markers as ordinary characters because they are inside the string.


Comment Examples

Single-Line

main.cpp
Run Online
// Calculate the total.
double total = price * quantity;

Multi-Line

main.cpp
Run Online
/*
    Calculate the total price
    using price and quantity.
*/
double total = price * quantity;

Documentation

main.cpp
Run Online
/**
 * Calculates the total price.
 *
 * @param price Price per item.
 * @param quantity Number of items.
 * @return Total price.
 */
double calculateTotal(double price, int quantity) {
    return price * quantity;
}

TODO

main.cpp
Run Online
// TODO: Add error handling.

FIXME

main.cpp
Run Online
// FIXME: Validate negative values.

C++ Comment Best Practices

Follow these practices when writing comments.

1. Explain intent

Tell readers why a non-obvious decision was made.

2. Keep comments concise

Use the smallest explanation that provides useful information.

3. Keep comments accurate

Update comments when the code changes.

4. Avoid repeating obvious code

Do not describe every simple statement.

5. Document public APIs

Functions, classes, and interfaces used by other developers often benefit from structured documentation.

6. Prefer clear code

Good naming and simple structure can reduce the need for comments.

7. Remove obsolete comments

Old comments can confuse future developers.

8. Use a consistent documentation style

If a project uses Doxygen, follow its established format.


Comments vs Documentation

Comments and documentation are related but are not exactly the same.

Comments

Usually help developers understand implementation details.

Example:

main.cpp
Run Online
// Ignore the first row because it contains column names.

Documentation

Usually describes how an API, class, function, or library should be used.

Example:

main.cpp
Run Online
/**
 * Calculates the total price.
 *
 * @param price Price of one item.
 * @param quantity Number of items.
 * @return Total price.
 */

Documentation is especially important for libraries and large applications.


Do Comments Increase Program Size?

In a normal compiled C++ application, comments are not executable instructions.

The compiler processes source code and the resulting executable does not normally contain ordinary source comments as executable code.

Therefore, adding a normal comment such as:

does not make the program perform an additional operation at runtime.

Comments primarily exist to improve the source code for humans and documentation tools.


A Practical C++ Example

Here is a small program using several useful commenting styles:

main.cpp
Run Online
#include <iostream>

// Calculate the sum of two integers.
int add(int a, int b) {
    return a + b;
}

/**
 * Program entry point.
 *
 * Demonstrates a simple function and output.
 */
int main() {
    int first = 10;
    int second = 20;

    // Calculate the result.
    int result = add(first, second);

    std::cout << "Sum = " << result << "\n";

    return 0;
}

Output:

This example demonstrates:

  • Single-line comments

  • Documentation-style comments

  • Functions

  • Variables

  • Function calls

  • Output


Frequently Asked Questions

What are comments in C++?

Comments are explanatory text in C++ source code that is ignored as executable code by the compiler. They are used to explain code and document programs.

How do you write a single-line comment in C++?

Use two forward slashes:

Everything after // on that line is treated as a comment.

How do you write a multi-line comment in C++?

Use /* to start the comment and */ to end it:

main.cpp
Run Online
/*
    This is a
    multi-line comment.
*/

What is the difference between // and /* */?

// creates a single-line comment, while /* ... */ can span multiple lines.

What are documentation comments in C++?

Documentation comments are specially formatted comments that documentation tools can process. Doxygen is a popular example.

For example:

main.cpp
Run Online
/**
 * Adds two numbers.
 *
 * @param a First number.
 * @param b Second number.
 * @return Sum of the numbers.
 */

Does C++ execute comments?

No. Comments are not executed as program instructions.

Can comments be used to disable C++ code?

Yes. Code can temporarily be placed inside comments, although long-term obsolete code is generally better removed and recovered through version control when needed.

Can C++ comments be nested?

Block comments using /* ... */ should not be treated as nestable comments. Nested block-comment syntax can cause unexpected results.

Should every line of C++ code have a comment?

No. Over-commenting can make code harder to read. Good code should be understandable through clear naming and structure, with comments added where they provide useful context.

Which comments should I use in C++?

Use // for short explanations and /* ... */ when a block comment is more appropriate. For public APIs, consider a consistent documentation style such as Doxygen.

Suggested Graphic Design

Create a clean programming infographic titled:

“C++ Comments: 3 Common Styles”

Show three side-by-side sections:

Architecture Diagram
┌─────────────────────┐
│  SINGLE-LINE        │
│                     │
│  // Explain code    │
│  int age = 25;      │
└─────────────────────┘

┌─────────────────────┐
│  MULTI-LINE         │
│                     │
│  /*                  │
│     Explain code     │
│     over lines       │
│  */                  │
└─────────────────────┘

┌─────────────────────┐
│  DOCUMENTATION      │
│                     │
│  /**                 │
│   * @param value     │
│   * @return result   │
│  */                  │
└─────────────────────┘

Add a small footer:

“Comments help people understand code — the compiler ignores ordinary comments.”

Suggested image alt text:
C++ comments guide showing single-line, multi-line, and documentation comment syntax with examples

Runnable Code Example: C++ Comments Guide

C++20 / C++23
main.cpp
Run Online
#include <iostream>

/**
 * @brief Calculates the total price including tax.
 * @param netPrice The base price of the item before tax.
 * @param taxRate The percentage tax rate (e.g., 0.18 for 18%).
 * @return double The gross calculated price.
 */
double calculateGrossPrice(double netPrice, double taxRate) {
    // Validate inputs are non-negative
    if (netPrice < 0.0 || taxRate < 0.0) {
        return 0.0;
    }

    /*
     * Computation formula:
     * gross = netPrice * (1.0 + taxRate)
     */
    double gross = netPrice * (1.0 + taxRate);
    return gross;
}

int main() {
    double total = calculateGrossPrice(100.0, 0.18);
    std::cout << "Calculated Gross Price: $" << total << "
";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: Can block comments /* */ be nested in C++?

A: No. The first `*/` encountered will close the entire block. To comment out code blocks containing existing comments, use `#if 0 ... #endif`.
Q

Q: What tool is used to parse C++ documentation comments into HTML?

A: Doxygen is the industry-standard documentation generator for C++ codebases.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Use #if 0 ... #endif to temporarily disable blocks of code containing comments.
2. Document public API headers thoroughly with Doxygen tags.
3. Write comments that explain the architectural intent and edge cases rather than repeating the syntax.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.