Thuta Learning
C
BasicProgrammingBeginner

Comments

CLesson 520 min

What you'll walk away with

  • Write single-line (//) and block (/* */) comments and say where each one ends
  • Explain why block comments do not nest and disable code safely with #if 0
  • Spot the trailing-backslash trap that makes a // comment swallow the next line
  • Write comments that explain reasons, units and assumptions instead of repeating the code

Explain it simply

Explain it simply

Comments are notes for people reading the code, including you a month from now. The compiler throws them away before it translates anything, so they never reach the program's output and cost nothing at run time. C has two kinds: // starts a note that runs to the end of the line, and /* ... */ wraps a note that can span many lines.

A comment is like a sticky note on a recipe: "use less salt, the stock is already salty". The recipe says what to do; the note says why, or what to watch out for. You do not need a note on every line, only where a reader would otherwise stop and wonder.

Problem → Why → Solution

The problem: comments that argue with the code

Look at this price list program. The first comment says it prints hello, but the code prints Price list. The second says tax is 5%, but the code multiplies by 1.07, which is 7%. The third says to remove a line "next week", and nobody knows which week or who should do it.

A teammate reads "tax is 5%" and reports a bug in your 7% calculation, or trusts the comment and "fixes" the code to 5%. Nothing in the code tells them which one is right.

prices.c
#include <stdio.h>

int main(void) {
    // print hello
    printf("Price list\n");

    // tax is 5%
    printf("Tea: %.2f\n", 1.50 * 1.07);

    /* TODO: remove this next week */
    printf("Coffee: %.2f\n", 2.00 * 1.07);
    return 0;
}

Why do comments start lying?

The compiler never reads comments, so it cannot tell you when one stops matching the code. Every comment is a second copy of some piece of knowledge, and copies drift apart. Comments that restate the code drift fastest, because every edit to the code has to be repeated in the comment. Good comments hold what the code cannot say: the reason, the source of a number, a warning.

Core concept: how comments disappear

C has two comment forms. A block comment starts with /* and ends at the first */ that follows, however many lines later. A line comment starts with // and ends at the end of the line; it was added in C99, although compilers accepted it as an extension long before. Inside a string literal neither form is special: printf("// not a comment\n") prints the slashes.

Comments disappear early. In the translation phases defined by the standard, each comment is replaced by a single space before preprocessing directives run, long before the compiler checks any types. So int/* note */count; reads as int count;, and a comment can never glue two tokens together. Comments on a directive line go the same way: #define WIDTH 80 /* columns */ defines WIDTH as just 80. Nothing about comments reaches the executable, so a well-commented program is exactly as fast as a bare one.

Two consequences follow from "ends at the first */". Block comments do not nest: /* outer /* inner */ is ... */ ends at the inner */, and the leftover text becomes a syntax error. And because line splicing happens even earlier, a backslash at the very end of a // line joins the next line onto the comment, silently deleting that line of code.

So what should a comment say? The most useful ones explain why the code is the way it is, give units and sources for numbers, state assumptions the code relies on and warn about traps. A file usually starts with a block comment describing its purpose. Comments that restate the code, such as /* add 1 to i */, add reading time without adding information.

Mental model: comments vanish before compiling
  1. Backslash-newlines are joined first
  2. Each comment becomes one space
  3. Directives run, then the compiler
  4. The executable has no trace of them

If deleting a comment would change what the code does, something is wrong: look for a stray */ or a trailing backslash.

General pattern

c
/*
 * file_name.c - what this file is for.
 * Block comments can span several lines.
 */

int main(void) {
    statement;               // line comment: runs to the end of this line
    statement;               /* block comment on a single line */
    result = a /* note */ + b;
    return 0;
}

Use a block comment for the file header and // for short notes beside a statement. A block comment may sit between two tokens, but it hurts readability, so use that sparingly.

Example: every comment form in one file

This program contains a file header, a line comment, a two-line block comment, a why comment, two comments inside an expression and comment markers inside a string. Watch the output: none of the comments appear, but the slashes inside the string do.

greeting.c
#include <stdio.h>

/*
 * greeting.c - prints the welcome banner for the course.
 * Block comments like this one work well as file headers.
 */

int main(void) {
    // Print a welcome message
    printf("Welcome to C!\n");

    /* This block can be used
       for longer notes. */
    printf("Comments make code easier to read.\n");

    // 80-column terminal minus a 4-column margin on each side
    printf("Text width: %d\n", 80 /* columns */ - 2 * 4 /* margins */);
    printf("// and /* inside quotes are just text */\n");
    return 0;
}

Code breakdown

  1. Lines 3-6 * greeting.c - prints the welcome banner for the course.

    A file header in a block comment. The * at the start of each line is only decoration; the comment ends at the */ on line 6.

  2. Line 9// Print a welcome message

    A line comment. It ends at the end of the line, so the printf below is ordinary code. A note this obvious is fine in a first program; in real code, prefer comments that add information.

  3. Lines 12-13/* This block can be used

    A block comment spanning two lines. Everything up to */ is ignored, line breaks included.

  4. Line 16// 80-column terminal minus a 4-column margin on each side

    A why comment: it explains where the numbers on the next line come from, which the code alone cannot say.

  5. Line 17printf("Text width: %d\n", 80 /* columns */ - 2 * 4 /* margins */);

    Comments may sit between tokens. Each one becomes a space, so the expression the compiler sees is 80 - 2 * 4, which is 72.

  6. Line 18printf("// and /* inside quotes are just text */\n");

    Inside a string literal, // and /* are ordinary characters, so this line prints them.

You should see
Welcome to C!
Comments make code easier to read.
Text width: 72
// and /* inside quotes are just text */

Disabling code: #if 0 instead of /* */

To switch off a chunk of code that already contains block comments, wrapping it in /* */ fails, because the first inner */ ends your comment. The preprocessor's #if 0 ... #endif removes every line in between, comments included, and nests safely. Delete the block once you no longer need it; version control keeps the old code.

disable.c
#include <stdio.h>

int main(void) {
    printf("start\n");
#if 0
    printf("debug: step 1\n");   /* temporary */
    printf("debug: step 2\n");   /* temporary */
#endif
    printf("done\n");
    return 0;
}

Documentation comments

Many projects put a comment starting with /** above each function declaration and use tags such as @param. To C it is an ordinary block comment, but tools such as Doxygen turn these into API documentation, and most editors show them when you hover over a call. In a header file it typically looks like this:

prices.h
/**
 * Returns the price including tax.
 * @param net   price before tax, in kyat
 * @param rate  tax rate as a fraction, e.g. 0.05 for 5%
 */
double with_tax(double net, double rate);

In real projects

How this shows up in real projects

Open almost any large C project and the first lines of each file are a comment. The Linux kernel starts its source files with an SPDX-License-Identifier comment that names the license in a machine-readable way, and many projects follow the header with a short description of the file's purpose. Tools read comments too: Doxygen turns the /** ... */ blocks above functions into browsable API documentation.

In code review, comments are where reviewers look for the reasoning. "Retry three times because the sensor sometimes returns a stale reading" tells the next maintainer the retries are deliberate. Teams also grep for TODO and FIXME markers, and a TODO is far more useful with a name, a date or an issue number attached. What reviewers push back on is commented-out code: git already remembers old versions, so dead code inside comments only confuses readers.

Common mistakes

Common mistakes

1. Nesting block comments

/* outer /* inner */ still outer */ does not work: the comment ends at the first */ and the rest is parsed as code. With -Wall, GCC warns "'/*' within comment" and then fails with an error such as "expected expression before '/' token". Use #if 0 to disable larger pieces of code.

2. A backslash at the end of a // comment

A line comment such as // path is C:\temp\ ends with a backslash, which joins the next line onto the comment. In a test program the following total = total + 5; vanished, so it printed 10 instead of 15, and the only sign was GCC's -Wall warning "multi-line comment". Put such paths in a block comment, or make sure the line does not end with a backslash.

3. Comments that repeat or contradict the code

// add 5 above total = total + 5; tells the reader nothing, and when someone later changes 5 to 7 the comment becomes a lie. Name things well, comment the reason, and update or delete comments in the same edit that changes the code.

Mini challenge

Mini challenge: a well-commented recipe

Write a program that prints a three-step milk tea recipe and uses every comment form from this lesson in the right place.

  • Start the file with a block comment header giving the file name and purpose
  • Put a why comment, not a what comment, above each step's printf
  • Compute the steeping time as 3 * 60 with an inline /* ... */ note inside the expression
  • Keep one debug printf in the file but disable it with #if 0 ... #endif
tea.c
// TODO: replace this line with a block comment header:
//       the file name and what the program does

#include <stdio.h>

int main(void) {
    // TODO: step 1 - print "1. Boil water (100 C)" and explain WHY above it

    // TODO: step 2 - print the steeping time in seconds, computed as
    //       3 * 60, with an inline /* ... */ note inside the expression

    // TODO: step 3 - print "3. Add milk" with a why comment

    // TODO: a debug printf that is disabled with #if 0 ... #endif

    return 0;
}

Expected: However many comments you add, the output shows only the three step lines: 1. Boil water (100 C) 2. Steep for 180 seconds 3. Add milk

Show hint

To test a why comment, read it with the code covered: if it only restates the code, replace it with the reason. #if 0 and #endif must each sit on a line of their own.

Show solution
tea.c
/*
 * tea.c - prints a three-step recipe for milk tea.
 * Written as practice for C comments.
 */

#include <stdio.h>

int main(void) {
    // Black tea needs fully boiling water to release its flavour.
    printf("1. Boil water (100 C)\n");

    // Longer steeping makes the tea bitter, so we stop at three minutes.
    printf("2. Steep for %d seconds\n", 3 * 60 /* minutes to seconds */);

    // Milk goes in last so it does not cool the water while steeping.
    printf("3. Add milk\n");

#if 0
    printf("debug: recipe printed\n");   /* enable while testing */
#endif
    return 0;
}

Quick quiz 1 / 3

What does printf("%d\n", 10 /* ten */ + 5); print?

Quick quiz 2 / 3

You wrap a piece of code in /* ... */, but it already contains a /* temporary */ comment. What happens?

Quick quiz 3 / 3

Which comment adds the most value above the line timeout = 86400;?

What to remember

  • // comments run to the end of the line; /* */ comments run to the first */, across lines.
  • Each comment becomes a single space before the compiler runs, so comments cost nothing at run time.
  • Block comments do not nest, and a backslash at the end of a // line swallows the next line; use #if 0 to disable code.
  • Comment the why, units and assumptions; delete comments that only restate the code and update the rest with every change.

GNU C compiler diagnostics — GNU Project

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Comments | Thuta Learning