C course menu
Comments in C: Single-line and Multi-line Comments
Learn to write comments in C: multi-line comments with /* */, single-line comments with //, why comments cannot be nested, using #if 0 to disable code, and how to write useful comments and documentation comments.
On this page
Comments are notes for people reading the code. The compiler ignores them completely.
Two kinds of comments#
#include <stdio.h>
/*
* A multi-line comment starts with slash-star
* and ends with star-slash.
*/
int main(void) {
int price = 250; // a single-line comment runs to the end of the line
printf("%d\n", price * 2); /* this style also works on one line */
return 0;
}500/* ... */comments can span many lines. They are the original C comment style.// ...comments run to the end of the line. They were added in C99 and are now standard.
Comments cannot be nested#
The first */ ends a /* */ comment, so putting one comment inside another breaks:
/* outer comment /* inner comment */ this text is now treated as code */This makes /* */ awkward for disabling a block of code that already contains comments. The preprocessor offers a better tool.
Disabling code with #if 0#
Code between #if 0 and #endif is removed before compiling, whatever it contains:
#include <stdio.h>
int main(void) {
printf("This line runs\n");
#if 0
printf("This line is disabled\n"); /* comments inside are fine */
#endif
printf("So does this one\n");
return 0;
}This line runs
So does this oneYou will learn more about #if in The Preprocessor and Macros.
Writing useful comments#
- Explain why, not what: the code already says what it does.
- Describe what a function expects and returns, especially for pointers (who owns the memory? can it be
NULL?). - Keep comments up to date; a wrong comment is worse than none.
/* Bad: repeats the code */
i = i + 1; /* add 1 to i */
/* Good: explains the reason */
i = i + 1; /* skip the header row */Many projects use Doxygen-style comments above functions, which tools can turn into documentation:
/**
* Returns the average of the first n values.
* @param values array of at least n numbers (must not be NULL)
* @param n number of values; must be greater than 0
*/
double average(const double *values, int n) {
double sum = 0;
for (int i = 0; i < n; i++) sum += values[i];
return sum / n;
}Practice#
Practice exercise
Add a comment to this program explaining why 100 is subtracted, and disable the second printf with #if 0:
#include <stdio.h>
int main(void) {
int balance = 1200 - 100;
printf("Balance: %d\n", balance);
printf("Debug: raw value 1200\n");
return 0;
}Show solution
#include <stdio.h>
int main(void) {
int balance = 1200 - 100; /* 100 is the monthly account fee */
printf("Balance: %d\n", balance);
#if 0
printf("Debug: raw value 1200\n");
#endif
return 0;
}Balance: 1100Key takeaway#
Finished this lesson?