Nearby lessons
14 of 124C - Comments in C
Comments are notes you leave inside your source code for people to read — the compiler skips them completely. C gives you two styles: // for a single line and /* ... */ for a block. This lesson covers both, what comments are good for, and the one rule beginners always trip over: block comments cannot be nested.
What are Comments?
A comment is a note you write inside your source code to explain what the code does. Comments are written for people (including your future self) — the compiler skips them completely while building the program.
Single-Line Comments (//)
Everything from // to the end of that line is a comment. Use it for one-line notes.
// comments out the rest of the line — and only that line. The next line is code again.
Multi-Line Comments (/* */)
To write a note that spans several lines, open with /* and close with */. Everything in between is ignored by the compiler. This is the usual way to write a header block at the top of a file.
Block Comments Do Not Nest
This is the one comment rule that catches everybody. A block comment ends at the first */ the compiler finds — not at the matching one. So you cannot put a /* */ comment inside another /* */ comment.
/* or */ inside a block comment.
/* Purpose : Show how /* */ works */
The comment closes at the */ in the middle of the sentence. The word works and the final */ are then left over as real code, and the compiler stops:
error: unknown type name 'works'
error: expected identifier or '(' before '/' token
The fix is simply to describe the syntax without typing it:
| Instead of | Write |
|---|---|
Purpose : Show how /* */ works |
Purpose : Show how block comments work |
Commenting out a block that already has /* */ in it |
Put // in front of each line instead |
/* is closed by the very next */. If you need to comment out code that already contains a block comment, use // on every line — single-line comments stack safely.
What Comments Can Do
- Explain tricky logic — a one-line note can save hours of reading.
- Document programs — header comments for author, date, purpose.
- Temporarily disable code — commenting a line stops it from running without deleting it.
// printf("hi"); print anything? No — the whole line is a comment, so the compiler never sees the printf at all.
- Comments explain code but are ignored by the compiler
- // marks a single-line comment
- /* ... */ marks a multi-line comment
- Comments never affect the output of a program
- Block comments do not nest — the first */ closes the comment