What are Comments in C Explained-Embedded C Programming Course Online

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Elements of C | Lecture 8

Comments in C Explained

Block comments, line comments, the nesting trap, the one-space rule and the backslash bug, with four tested programs from our free embedded systems course.

2
comment styles
4
tested examples
8
quiz questions

Good comments in C turn a working program into one that a teammate can understand six months later. The compiler throws comments away completely, yet they are one of the first things a reviewer or interviewer looks at when judging your code. In this lecture of our free embedded systems course you will learn how block comments and line comments work, where they may appear, why they cannot be nested and what really happens to them during compilation.

We also cover the traps that catch even experienced engineers: a comment that swallows real code, a backslash that extends a line comment, and the safe way to switch off a large chunk of code. These habits matter just as much in the free Linux device drivers course as in a small microcontroller project, because kernel and driver code lives for years and is read by many people.

What You Will Learn

  • The two comment styles in C: /* ... */ and // ..., and which standard introduced each
  • Where a comment may be written and where it is only text
  • Why comments cannot be nested, and how to disable code safely with #if 0
  • What the preprocessor does with a comment: it becomes one space
  • The backslash trap that makes a line comment swallow the next line
  • How to write comments that explain why, not what
  • A simple documentation-comment style for functions
  • Interview questions on comments in C

Prerequisites

You should have read the lectures on expressions and statements in C, and be able to compile a program with gcc. Nothing else is needed.

Keywords in this lecture

comments in Cblock commentline commentnested comments#if 0preprocessorcode readabilityfree embedded systems coursefree linux device drivers courseC interview questions

What Are Comments in C?

A comment is text written for humans. It explains the purpose of a program, a function or a tricky line, and the compiler ignores it. Comments make code easier to read, review and maintain, but they have no effect on the generated machine code.

C offers two styles. The original block comment starts with /* and ends at the next */, and can cover one line or many. The line comment starts with // and runs to the end of the physical line. Line comments were added in the C99 standard, borrowed from C++, so a strict C89 compiler rejects them.

StyleSyntaxEnds atStandard
Block comment/* text */the first */, can span linesC89 and later
Line comment// textend of the lineC99 and later

Two comment styles at a glance

/* explains this section */block: any length, closes with */
int mv = adc * 3300 / 4095; // scaleline: to the end of the line

Example 1: Block and line comments together

/*
 * e8_1.c - block comment spanning several lines.
 * Purpose: convert a battery ADC count into millivolts.
 */
#include <stdio.h>

/* Reference voltage of the ADC, in millivolts */
#define VREF_MV 3300

int main(void)
{
    int adc = 2048;                 // 12-bit count (C99 line comment)
    int mv  = adc * VREF_MV / 4095; /* scale to millivolts */

    printf("adc=%d -> %d mV\n", adc, mv);   // output line
    return 0;
}
gcc -std=c17 -Wall -Wextra e8_1.c -o e8_1
./e8_1
Predict the output, then click to check

The comments do not change the result. Work out 2048 * 3300 / 4095 using integer arithmetic.

adc=2048 -> 1650 mV

The output is 1650 mV: the ADC reading is about half of full scale, so the voltage is about half of the 3300 mV reference. The file opens with a multi-line block comment that states the purpose, a one-line block comment documents the constant, and the two line comments annotate the code they sit beside.

Because older compilers reject //, you can see what a strict C89 build says. The same file, compiled with -std=c89 -pedantic, produces:

e8_1.c: In function ‘main’:
e8_1.c:12:37: error: C++ style comments are not allowed in ISO C90
   12 |     int adc = 2048;                 // 12-bit count (C99 line comment)
      |                                     ^

If you must support an ancient toolchain, stick to /* */. Modern projects built with C99 or later can use both, but many style guides still choose one style for consistency. For kernel code, read the coding-style document of the tree you are working on.

Where Can Comments Be Written in C?

You may place a comment almost anywhere that whitespace is allowed: between statements, at the end of a line, between function arguments or inside a long expression. The exception is inside a string literal or a character constant, where /* and // are just characters.

Allowed and not a comment

between tokensint /* count */ n = 0;fine
end of linen++; // next itemfine
inside a string“/* not a comment */”plain text
inside a char constant‘/’plain character

Why Comments in C Cannot Be Nested

A block comment ends at the first */ that follows its opening /*. The compiler does not count levels of opening markers. So when you wrap code that already contains a block comment inside another block comment, the outer comment ends too early, and the remaining text is read as real code.

What the compiler sees in Example 2

line 1/* disable the debug blockcomment opens
line 2-3printf(…); /* first message */comment closes at this */
line 4printf(“step 2\n”);now treated as real code
line 5*/stray closing marker, syntax error

Example 2: The nesting trap and the safe alternative

The first file tries to switch off two statements by wrapping them in a comment. One of them carries its own comment.

#include <stdio.h>

int main(void)
{
    /* disable the debug block
    printf("step 1\n");   /* first message */
    printf("step 2\n");
    */
    printf("done\n");
    return 0;
}
gcc -std=c17 -Wall -Wextra e8_2_bad.c -o bad
Predict what the compiler says, then click to check
e8_2_bad.c: In function ‘main’:
e8_2_bad.c:6:27: warning: "/*" within comment [-Wcomment]
    6 |     printf("step 1\n");   /* first message */
      |                            
e8_2_bad.c:8:6: error: expected expression before ‘/’ token
    8 |     */
      |      ^

GCC first warns that it found /* inside a comment (-Wcomment), then fails at the stray */. The robust way to remove a block of code is the preprocessor:

#include <stdio.h>

int main(void)
{
#if 0
    printf("step 1\n");   /* first message */
    printf("step 2\n");
#endif
    printf("done\n");
    return 0;
}
gcc -std=c17 -Wall -Wextra e8_2_good.c -o good
./good
Check the output
done

#if 0 ... #endif removes everything between the two lines before the compiler parses it, and it nests properly with other comments and with other #if blocks. Remember to delete dead code before committing: version control, not comment blocks, is where old code should live.

What Happens to a Comment During Compilation?

Before the compiler analyses your program, the preprocessor runs. In one of its early translation phases every comment is replaced by a single space. That means a comment separates tokens exactly like a space does, and it can never glue two tokens together.

Translation of a source line

int/**/count = 10;what you wrote
comment becomes one spaceint count = 10;what the compiler reads

Example 3: Comment markers inside strings, and the one-space rule

#include <stdio.h>

int main(void)
{
    printf("/* this is just text */\n");
    printf("// so is this\n");
    char slash = '/';
    char star  = '*';
    printf("slash=%c star=%c\n", slash, star);
    printf("a" /* comment between literals */ "b\n");
    return 0;
}
gcc -std=c17 -Wall -Wextra e8_3.c -o e8_3
./e8_3
Predict the output, then click to check
/* this is just text */
// so is this
slash=/ star=*
ab

The two printf calls print the marker characters because they sit inside string literals. The character constants '/' and '*' are plain characters too. The last line shows two adjacent string literals separated by a comment: the comment becomes a space, the literals concatenate, and the output is ab.

To see the one-space rule directly, run only the preprocessor on this two-line file. The second line is deliberately wrong:

int/**/count = 10;
int total = 1/**/2;
gcc -E -P e8_3c.c
Check what the preprocessor produced
int count = 10;
int total = 1 2;

In the first line the comment between int and count became a space, which is still a valid declaration. In the second line 1/**/2 became 1 2, two separate numbers, so the compiler rejects it:

e8_3c.c:2:18: error: expected ‘,’ or ‘;’ before numeric constant
    2 | int total = 1/**/2;
      |                  ^

Do not rely on old tricks

Pre-standard C compilers pasted tokens together by writing a/**/b, and you may meet that trick in very old code. Standard C replaces the comment with a space, so token pasting must use the ## operator instead. Never write code that depends on the old behaviour.

The Backslash Trap in Line Comments

A backslash at the very end of a physical line joins that line with the next one before comments are recognised. If a // comment ends with a backslash, the following line becomes part of the comment, and real code silently disappears.

Example 4: A line comment that swallows code

#include <stdio.h>

int main(void)
{
    int limit = 10;
    // check the limit \
    limit = 99;
    printf("limit = %d\n", limit);
    return 0;
}
gcc -std=c17 -Wall -Wextra e8_4.c -o e8_4
./e8_4
Predict the output, then click to check

Will limit become 99? Read the warning too.

e8_4.c: In function ‘main’:
e8_4.c:6:5: warning: multi-line comment [-Wcomment]
    6 |     // check the limit \
      |     ^
limit = 10

The program printed 10, not 99. The assignment limit = 99; was absorbed into the comment on the line above, and the compiler only hinted at it with multi-line comment from -Wcomment. This bug is common in Windows paths written in comments, such as // copy to C:\drivers\. Never end a line comment with a backslash, and keep -Wall switched on so the warning is visible.

How to Write Good Comments in C

The best comment is the one the code does not need, because a clear name already says everything. When a comment is needed, it should explain why, not repeat what the code already shows.

Weak commentBetter comment
i++; /* add one to i */i++; /* skip the header byte */
delay(5); /* wait */delay(5); /* sensor needs 5 ms after power-up (datasheet 7.3) */
x = x & 0xF7; /* and with F7 */x &= ~LED_ENABLE_BIT; /* switch the LED off, keep other bits */

A short block comment above a function that states its purpose, inputs, outputs and any constraint helps both humans and documentation tools. A simple style looks like this:

/**
 * ep_scale_adc - convert a raw ADC count to millivolts
 * @count: 12-bit ADC reading, 0 to 4095
 * @vref_mv: reference voltage in millivolts
 *
 * Return: voltage in millivolts, rounded down.
 * Context: safe to call from interrupt handlers (no blocking).
 */
static int ep_scale_adc(int count, int vref_mv)
{
    return count * vref_mv / 4095;
}

Tools such as Doxygen and the kernel-doc script read comments of this form. The first line holds the function name and a one-line summary, followed by the parameters. In hardware code, comments are also the right place to record register addresses, units, timing limits and the datasheet section you used.

Common Mistakes with Comments in C

MistakeResultFix
Nesting /* */ to disable codeComment ends early, syntax errorUse #if 0 ... #endif
Forgetting to close a block commentCode after it disappears, or a compiler error at end of fileUse an editor that highlights comments, keep -Wall on
Ending a // comment with a backslashNext line is swallowedNever end comment lines with \
Comments that repeat the codeNoise, and they go staleExplain intent, units and constraints
Leaving commented-out code in the fileConfuses readers and hides bugsDelete it, version control keeps history
Using // with a strict C89 buildCompiler errorUse /* */ or compile with C99 or later

Best practices

  • Comment the why: assumptions, hardware quirks, units and datasheet references.
  • Update comments in the same edit as the code. A wrong comment is worse than none.
  • Pick one comment style per project and follow the project’s style guide.
  • Use #if 0 for temporary removal and #ifdef DEBUG for debug-only code you want to keep.
  • Never put secrets such as passwords or private keys in comments. They end up in repositories and in source tarballs.

Performance note: comments cost nothing at run time and nothing in the binary. They are removed before compilation, so describe as much as helps. Security note: comments can mislead reviewers. A comment that claims a buffer is checked while the code does not check it is a classic source of vulnerabilities, so review what the code does, not what the comment says.

Quiz: Test Your Understanding of Comments in C

Q1. Which standard added the // comment to C?

C99. Strict C89 compilers reject it.

Q2. Can a block comment contain another block comment?

No. The first */ ends the comment, so the nested opening marker has no effect and the outer closing marker becomes a syntax error.

Q3. What is printed by printf("// hello");?

// hello. Inside a string literal the markers are just text.

Q4. What does the preprocessor replace a comment with?

A single space character.

Q5. How do you safely disable thirty lines of code that already contain comments?

Wrap them in #if 0 and #endif.

Q6. Why is a trailing backslash dangerous after a // comment?

It joins the next line to the comment, so that line of real code is ignored.

Q7. Does a comment increase the size of the compiled binary?

No. Comments are removed before compilation.

Q8. Which is the better comment: /* increment i */ or /* skip the 2-byte header */?

The second. It explains the reason, while the first repeats what the code already says.

Interview Questions on Comments in C

1

Are comments in C nestable?

Show answer

No. A block comment ends at the first */. Use #if 0 to disable code that contains comments.

2

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

Show answer

The first can span several lines and is available in all C standards. The second runs to the end of the line and exists from C99 onward. Both are removed in the preprocessing stage.

3

What does int/**/x; mean in standard C?

Show answer

The comment becomes a space, so it is the declaration int x;. It does not paste int and x together.

4

Predict the result: int a = 5; // set a \ followed by the next line a = 9;.

Show answer

a stays 5. The backslash splices the next line into the comment, so a = 9; never executes.

5

How would you leave debug code in the source but out of the release build?

Show answer

Wrap it in #ifdef DEBUG ... #endif and define DEBUG only for debug builds, for example with -DDEBUG.

6

What makes a comment useful in firmware code?

Show answer

It records information the code cannot show: units, datasheet references, timing limits, why a delay exists, and which context (interrupt or thread) a function is safe in.

Summary and Key Takeaways

  • Comments in C come in two styles: block /* */ from C89 and line // from C99.
  • They are removed during preprocessing, each replaced by a single space, so they never affect the binary.
  • Comment markers inside string or character constants are ordinary text.
  • Block comments do not nest. Use #if 0 to disable code safely.
  • A backslash at the end of a line comment splices in the next line, a classic silent bug.
  • Write comments that explain why, keep them current and follow your project style.

Conclusion

You now understand comments in C well enough to use them safely and to explain their rules in an interview. They look simple, but the nesting limit, the one-space replacement and the backslash splice are exactly the details that separate careful engineers from careless ones. With this lecture the Elements of C chapter on expressions, statements and comments is complete. In the next chapter we move on to the operators in detail, building directly on what you learned about expressions. Keep following the free embedded systems course and the free Linux device drivers course to build a strong foundation for product-company interviews.

Frequently Asked Questions About Comments in C

What are comments in C?

Comments are text for human readers that the compiler ignores. C supports block comments written between /* and */ and, since C99, line comments that start with //.

Can I nest comments in C?

No. A block comment ends at the first */ after its start, so a nested comment ends the outer one early. Use #if 0 and #endif to disable code that already contains comments.

Does the compiler support // comments?

Yes for C99 and later, which includes the default modes of modern GCC and Clang. Strict C89 mode rejects them.

Do comments slow down my program or make it larger?

No. Comments are removed during preprocessing and do not appear in the compiled binary.

Why did my line after a // comment not run?

If the comment line ends with a backslash, the next line is joined to it and becomes part of the comment. Remove the trailing backslash.

How should I comment out a large block of code?

Use #if 0 and #endif around the block. It works even when the block contains other comments.

Where can I learn C comments and style for free?

EmbeddedPathashala’s free embedded systems course and free Linux device drivers course teach comments, style and interview topics with tested examples.

Chapter Complete: Elements of C

You have covered expressions, statements and comments. Continue with operators in the free embedded systems course to put expressions to work.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *