Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 135 ยท Getting Started

Comments

Learn C comments - block comments with /* */, line comments with //, why block comments do not nest, documenting functions, and useful habits.

A comment is text in your source code that the compiler ignores. Comments exist only for people: the colleague who reads your code next month, the maintainer who inherits it in five years, and you, after you've forgotten why you wrote it that way. The preprocessor removes them before compilation, so they never make your program bigger or slower.

C has two kinds of comments. This lesson covers both, the traps that come with each, how to document functions so that tools and humans can use the documentation, and the habits that separate useful comments from noise.

Block comments: /* ... */

The original C comment starts with /* and ends with the next */. Everything in between is ignored, even if it spans many lines:

C Block comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program prints Hello and World; the comments have no effect. The column of * characters at the start of each line in the first comment isn't required, it's just a popular style that makes the comment's extent obvious.

A block comment can appear anywhere whitespace can, even in the middle of a statement as the second printf shows. The compiler treats the whole comment as if it were a single space. That means you can't use a comment to glue two words together: int/**/x is int x, and pri/**/ntf is two separate words.

Line comments: //

C99 added the line comment: // starts a comment that runs to the end of the line. It's shorter to type and the most common style in modern C:

C Line comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints Total: 37.50. Line comments are ideal for short notes above or beside a line of code.

Note: Very old C code (C89/C90) uses only /* */, because // wasn't standard yet. Some coding standards for embedded projects still require block comments. Every compiler you're likely to use today accepts both.

Block comments don't nest

The biggest trap with /* */ is that it ends at the first */, no matter how many /* came before. You can't put one block comment inside another. That bites when you try to "comment out" code that already contains a block comment. This example fails to compile on purpose:

C Nested block comments break

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The outer comment ends at the */ after first step. The following printf("Step 2\n"); is ordinary code again, and the lone */ on the next line is a syntax error (expected expression before '/' token). Before that error, GCC warns '/*' within comment (-Wcomment), pointing at the inner /*. That warning is your clue.

Line comments don't have this problem, because each one ends at the end of its own line. Most editors comment out a selection by adding // to every line (often with the shortcut Ctrl+/ or Cmd+/).

Disabling code with #if 0

To switch off a large chunk of code that may contain comments of either kind, use the preprocessor instead:

C Switching code off with #if 0

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The preprocessor drops everything between #if 0 and #endif, so only the first and last lines print. Change 0 to 1 to bring the code back. This is a handy tool while debugging, but don't leave disabled code lying around in finished programs: version control (like Git) remembers old code far better than comments do.

Comment edge cases

A few rules prevent surprises:

  • Inside string literals, comment markers are just characters. printf("// not a comment\n"); prints // not a comment. The same is true for /* inside a string.
  • A backslash at the end of a // line continues the comment onto the next line. The preprocessor joins lines that end with \ before it removes comments, so the next line becomes part of the comment and silently disappears. GCC warns multi-line comment.
  • Comments can't start inside a character constant or a string, so '/' followed by '*' is two characters, not a comment.

Here's the backslash trap. The program compiles, but one statement vanishes:

C A backslash swallows a line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

You'd expect files = 1, but it prints files = 0: the trailing \ turned files = files + 1; into part of the comment. GCC flags it with warning: multi-line comment [-Wcomment]. Another reason to read every warning.

Documenting functions

The most valuable comments sit above a function and explain its contract: what it does, what each parameter means, what it returns, and what the caller must guarantee. Someone calling the function should never need to read its body.

Many C projects use the Doxygen style, which a documentation generator can turn into web pages and which editors show as tooltips:

C
/**
 * Computes the average of the first `count` values in `values`.
 *
 * @param values  array of readings; must not be NULL when count > 0
 * @param count   number of readings to use
 * @return        the average, or 0.0 when count is 0
 */
double average(const double values[], int count);

The block starts with /** (two stars), and tags like @param and @return mark the parts. Other projects use plain comments with the same information. What matters is that the contract is written down, especially edge cases: what happens with zero, with NULL, with negative numbers, and who is responsible for freeing returned memory.

Here's a complete program with a documented helper function:

C A documented function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints a four-row table, from -40.0 C = -40.0 F to 100.0 C = 212.0 F. You'll learn to write functions like this in Functions.

Writing good comments

A comment is good when it tells the reader something the code can't. Compare:

C
i = i + 1;            // add 1 to i                         (useless)
retries = retries + 1; // the server drops the first request
                       // after a restart, so we always retry once  (useful)

The first comment repeats the code. The second explains why, which no amount of reading the code would reveal. Some guidelines:

  • Explain why, not what. Good names (see Keywords and Identifiers) and clear code explain what happens. Comments explain intent, reasons, and decisions you rejected.
  • Document the non-obvious. Units (// in milliseconds), valid ranges, ownership of memory, thread-safety, and anything surprising.
  • Keep comments true. An outdated comment is worse than none, because readers trust it. When you change code, update the comments next to it.
  • Prefer clearer code over a clever comment. If you need a long comment to explain a confusing expression, try rewriting the expression first, or move it into a well-named function.
  • Mark unfinished work consistently. Many teams use // TODO: for planned work and // FIXME: for known bugs, so they're easy to search for.
  • Put a short header at the top of each file saying what the file is for. Large projects often add license information there too.

Tip: Avoid comments like // end if or // end of main after closing braces. If a block is so long that you need them, the function is probably too long and should be split up.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? printf("a /* b */ c\n");

    Comment markers inside a string literal are ordinary characters, so the whole text is printed unchanged.
  2. 2. Why does wrapping code that contains a /* ... */ comment in another /* ... */ fail?

    The outer comment ends at the inner comment's */. The rest is treated as code, usually causing a syntax error.
  3. 3. Which is the safest way to temporarily disable 50 lines that contain block comments?

    The preprocessor removes everything between #if 0 and #endif, regardless of what comments the lines contain.
  4. 4. A line reads // path is C:\data\ and the next line is count++;. What happens to count++;?

    A backslash at the end of a line joins it with the next line before comments are removed, so count++; ends up inside the // comment. GCC warns about a multi-line comment.
  5. 5. Which comment adds the most value?

    It gives the unit and the reason for the value, which the code alone can't tell you. The others just repeat what the code already says.

Summary

  • Comments are removed before compilation; they cost nothing at run time.
  • /* ... */ comments can span lines but end at the first */, so they don't nest.
  • // comments (C99) run to the end of the line; a trailing backslash extends them, which can swallow code.
  • Use #if 0 ... #endif to disable a block of code temporarily.
  • Document each function's contract (parameters, return value, edge cases), for example in Doxygen /** ... */ style.
  • Good comments explain why, give units and limits, and stay in sync with the code.

Next: Printing Output with printf, where you'll learn every format specifier you need.