How To Comment In C Language

9 min read

Comments in C are non-executable lines of text embedded within source code to explain the logic, purpose, or functionality of specific sections. Even so, they serve as internal documentation, allowing developers—including your future self—to understand the why behind the code without deciphering complex syntax. That said, mastering the art of commenting is a fundamental skill that separates maintainable, professional codebases from fragile, confusing scripts. This guide explores the syntax, types, best practices, and advanced strategies for commenting effectively in the C programming language.

The Two Types of Comments in C

Standard C supports two distinct commenting styles, each with specific use cases and behavioral characteristics. Understanding the difference is the first step toward writing clean code.

Single-Line Comments (C99 and Later)

Introduced in the C99 standard, single-line comments begin with two forward slashes (//). So everything following these characters on the same line is ignored by the compiler. This style is ideal for brief annotations, variable explanations, or temporarily disabling a single line of code Still holds up..

The official docs gloss over this. That's a mistake Easy to understand, harder to ignore..

#include 

int main() {
    int score = 95; // Initialize player score
    // printf("Debug: Score is %d\n", score); // Temporarily disabled debug line
    return 0;
}

Key characteristics:

  • Scope: Terminates automatically at the end of the line (newline character).
  • Nesting: Cannot be nested inside another // comment (redundant).
  • Portability: Supported by all modern compilers (GCC, Clang, MSVC) in default modes. If you are maintaining legacy C89/C90 codebases, this syntax may trigger warnings or errors unless the compiler is set to a newer standard (e.g., -std=c99 or -std=c11).

Multi-Line Comments (Block Comments)

This is the original C commenting style, inherited from B and BCPL. It uses a start delimiter /* and an end delimiter */. The compiler ignores everything between these markers, spanning across multiple lines. This is the only option available in strict C89/C90 environments.

This is where a lot of people lose the thread.

/*
 * File: calculator.c
 * Author: Jane Doe
 * Description: A simple program to demonstrate block comments.
 * Date: 2023-10-27
 */

#include 

int add(int a, int b) {
    /* This function returns the sum of two integers.
       It handles standard integer overflow behavior defined by C standard. */
    return a + b;
}

Key characteristics:

  • Scope: Spans multiple lines until the closing */ is encountered.
  • Nesting Restriction: Standard C does not support nesting block comments. Attempting to nest /* ... /* ... */ ... */ will result in a compilation error because the first */ closes the outer comment, leaving the remaining */ as a syntax error.
  • Documentation Generation: Tools like Doxygen rely heavily on specially formatted block comments (often starting with /**) to generate external API documentation automatically.

How the Preprocessor Handles Comments

It is crucial to understand that comments are stripped out during the preprocessing phase (Phase 3 of translation), effectively replaced by a single space character. They do not exist in the compiled binary, do not increase executable size, and incur zero runtime performance penalty.

Not the most exciting part, but easily the most useful.

Even so, this removal happens before string literal parsing. Because of this, comment delimiters inside string literals or character constants are treated as literal characters, not comment markers.

printf("This is not a comment: /* ... */ // ..."); // Valid string
char c = '/'; // Valid character constant
// char c = '/*'; // Error: multi-character constant

Best Practices for Effective Commenting

Writing comments is easy; writing good comments requires discipline. The goal is to clarify intent, not to translate code into English.

1. Explain "Why," Not "What"

The code itself shows what is happening. Comments should explain why a specific approach was chosen, why a magic number exists, or what the business logic dictates.

❌ Bad (Redundant):

i = i + 1; // Increment i by 1

✅ Good (Contextual):

retry_count++; // Increment retry counter to track connection attempts

2. Keep Comments Synchronized

Outdated comments are worse than no comments at all; they actively mislead developers. Treat comments as part of the code: if you refactor a function, update its header comment and relevant inline notes immediately.

3. Use Header Blocks for Files and Functions

Every source file (.c) and header file (.h) should start with a standard header block. For functions, use a consistent format (like Doxygen/Javadoc style) describing parameters, return values, and side effects.

/**
 * @brief Calculates the factorial of a non-negative integer.
 * @param n The input number (must be >= 0).
 * @return The factorial result, or -1 if input is invalid/overflow.
 * @note This function uses recursion. Stack overflow risk for large n.
 */
long long factorial(int n) {
    if (n < 0) return -1;
    if (n == 0) return 1;
    return n * factorial(n - 1);
}

4. Avoid "Commented-Out Code" Graveyards

It is tempting to comment out large blocks of old logic "just in case." Do not do this. Version control systems (Git, SVN) exist for history. Commented-out code rots, creates visual noise, and confuses readers about the active logic flow. Delete it; retrieve it from history if needed.

5. Standardize TODO/FIXME Tags

Use standardized tags for technical debt tracking. Many IDEs parse these into task lists.

  • // TODO: Implement error handling for null pointer.
  • // FIXME: Memory leak detected in buffer allocation.
  • // HACK: Temporary workaround for API bug v1.2; remove when upgraded.

Advanced Commenting Strategies

Conditional Compilation vs. Comments

For disabling large code blocks during debugging or cross-platform development, prefer preprocessor directives over block comments. This avoids the nesting problem entirely.

#if 0
/* This entire block is disabled.
   Nested comments /* like this */ are safe here. */
void legacy_function() { ... }
#endif

The #if 0 block is ignored by the compiler but parsed by the preprocessor, meaning syntax errors inside it might still be flagged (depending on compiler flags), keeping the code "alive" structurally.

Documenting Data Structures

Complex struct definitions benefit immensely from field-by-field comments, especially regarding units, valid ranges, or ownership semantics (who frees the memory?).

typedef struct {
    char *buffer;      /**< Dynamically allocated data buffer. Owned by this struct. */
    size_t capacity;   /**< Total allocated size in bytes. */
    size_t length;     /**< Current valid data length in bytes. Must be <= capacity. */
    bool is_readonly;  /**< If true, buffer must not be modified or freed. */
} DynamicBuffer;

Licensing and Copyright Headers

In professional and open-source projects, the very first lines of a file are often a legal comment block specifying the license (MIT, GPL, Apache, Proprietary). This is mandatory for compliance Nothing fancy..

/*
 * Copyright (c) 2023 Your Company Name.
 * Licensed under the MIT License. See LICENSE file in project root.
 */

Common Pitfalls and How to Avoid Them

The Nesting Trap

As noted, /* /* nested */ */ fails. Solution: Use #if 0 ... #endif for blocking out code containing block comments

6. Integrating Comments with Your Development Workflow

6.1. Version‑Control‑Aware Commenting

When you add or modify comments, treat them like any other commitable artifact That's the whole idea..

  • Descriptive commit messages – Explain why a comment was added or updated, not just what it says.
  • Link to issues – Use Co-authored-by: or Fixes: trailers to tie comment changes to tickets or PRs.
  • Review discipline – Include comment changes in pull‑request reviews; stale or misleading comments are just as harmful as stale code.
# Example commit that adds a clarifying comment
git add src/network.cpp
git commit -m "Add comment about IPv6 fallback path
: co-authored-by: Jane Doe "

6.2. Automated Comment Linting

Static analysis tools can now enforce comment quality.

  • ** cppcheck‑comment** – Flags undocumented public APIs, missing TODO tags, or overly verbose block comments.
  • ** clang‑tidy‑misc** – Detects “dead” comments that refer to code no longer present.
# Run a comment‑focused linter on the whole project
cppcheck --enable=commentStyle ./src

Enable these checks in your CI pipeline so that comment drift is caught early, not discovered months later during a code audit That's the whole idea..

6.3. Comment‑Driven Documentation Generation

Many projects now harvest carefully‑formatted comments to produce API docs automatically (e.g., Doxygen, Javadoc, Sphinx). To make the most of this, adopt a consistent comment schema:

/**
 * @brief   Computes the n‑th Fibonacci number.
 * @param   n  Non‑negative integer index.
 * @return  Fibonacci number at position n. Returns -1 if n < 0.
 *
 * This function uses an iterative approach to avoid recursion depth limits.
 * For large n, consider using matrix exponentiation for O(log n) performance.
 */
int64_t fibonacci(int64_t n);

Notice the use of @brief, @param, @return, and an extra paragraph that explains performance considerations—information that belongs in the comment but not in the signature Not complicated — just consistent. Practical, not theoretical..

6.4. Comment Hygiene: Aging and Retirement

Comments, like any documentation, have a shelf life.

  • Tag aging – Append @deprecated or @obsolete tags to comments that reference soon‑to‑be‑removed features.
  • Scheduled cleanup – Allocate a recurring sprint (e.g., quarterly) to audit and prune outdated remarks.
/**
 * @deprecated Use `modern_api()` instead.
 * The legacy `old_api()` will be removed in v3.0.
 */
void old_api(int x);

6.5. Self‑Documenting Code Meets Comments

The best comment is sometimes no comment—because the code itself tells the story But it adds up..

  • Descriptive naming – std::vector<User> active_users; needs less explanation than std::vector<User> u;.
  • Type aliases – using Json = nlohmann::json; clarifies intent without a comment.
  • Const correctness – const std::string& path signals immutability instantly.

When naming alone cannot convey nuance (e.Day to day, g. , ownership, thread‑safety, or performance trade‑offs), supplement with a concise comment rather than a verbose paragraph Small thing, real impact..

6.6. Visual Consistency and Tooling Support

Maintain a uniform comment style across the codebase.

  • Indentation – Use two spaces for block comment indentation to align with surrounding code.
  • Punctuation – End most comment sentences with a period; omit them for single‑word tags (TODO, FIXME).
  • Line length – Keep comment lines ≤ 80 characters for readability on narrow terminals.

Many IDEs and linters

Many IDEs and linters now offer real-time comment highlighting, spell-checking for prose, and even AI-assisted comment generation. Configure your editor to surface comment warnings inline, and integrate tools like clang-tidy, pylint, or eslint with comment-specific rules into your pre-commit hooks. This creates a tight feedback loop: developers fix comment issues as they write, rather than during a separate review pass.

7. Conclusion

Comments are not secondary to code—they are part of the codebase’s living documentation. Treat them with the same rigor: review them in pull requests, lint them in CI, retire them when they age, and delete them when the code speaks clearly enough on its own. The goal is not more comments, but better comments: precise, current, and worth the reader’s time. When comments and code evolve together, they reduce onboarding friction, prevent costly misunderstandings, and keep the project maintainable long after the original author has moved on. Write comments for the future developer who will thank you—because that developer might be you.

Just Went Up

Hot Off the Blog

In the Same Zone

You May Enjoy These

Thank you for reading about How To Comment In C Language. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home