C Comments
What Are Comments?
Comments are notes you add to your source code to explain what it does. They are ignored by the compiler and have no effect on the program’s execution (they are removed during translation).
They are useful for explaining logic, reminding yourself of tasks, or documenting code for others.
#include <stdio.h>
int main(void) {
// This is a single-line comment
printf("Hello, World!\n");
return 0;
}
Hello, World!
Types of Comments in C
C supports two kinds of comments:
1. **Single-line comments** start with `//` and extend to the end of the line (standardized in C99).
2. **Multi-line (block) comments** start with `/*` and end with `*/` and can span several lines.
/* This is a multi-line comment
It can span multiple lines
and is ignored by the compiler */
#include <stdio.h>
int main(void) {
// Output a message
printf("Comments are ignored!\n");
return 0;
}
Comments are ignored!
Historical Note
The `//` (single-line) comment syntax was added to the C standard in **C99**. In pre-C99 code, only `/* ... */` was portable, although many compilers supported `//` as an extension.
Nesting and Large Blocks
`/* ... */` comments **do not nest**. Avoid commenting out a large region that already contains block comments, or you may get a compile error.
To temporarily disable large blocks of code safely, prefer the preprocessor guard pattern:
#include <stdio.h>
int main(void) {
#if 0
/* Big block of code
that may itself contain /* block comments */
is safely skipped here. */
printf("not compiled\n");
#endif
printf("compiled\n");
return 0;
}
compiled
Why Use Comments?
1. **Documentation**: Explain the purpose of variables, functions, or blocks of code.
2. **Debugging**: Temporarily disable parts of code by commenting them out (prefer `#if 0` for large blocks).
3. **Collaboration**: Help teammates understand your logic.
4. **Maintenance**: Make it easier to modify or extend code in the future.
Good Practices for Comments
- Write clear and concise comments; avoid redundancy with the code.
- Update comments whenever the code changes.
- Use comments to explain *why* something is done, not just *what* is done.
- Avoid commenting out long regions with `/* ... */` if they might contain `/* ... */` inside—use `#if 0` / `#endif` instead.
Too many unnecessary comments can clutter your code, so balance is important.
Practice | Example |
---|---|
Good | // Calculate total price with tax |
Bad | // Add x and y int z = x + y; |