C Comments
A comment is text in the code that the compiler ignores. Comments are for people: they explain why the code does something, mark sections of a long program, or switch a line off while you test.
Single-line comments
Two slashes // start a comment that runs to the end of the line. It can stand on its own line or after a statement.
#include <stdio.h>
int main(void) {
// Print a greeting
printf("Hello\n"); // this comment is ignored too
return 0;
}Hello
Multi-line comments
/* starts a comment that continues until */, even over several lines. Older C code (before C99) only had this kind.
#include <stdio.h>
int main(void) {
/* This program prints two lines.
The second printf is switched off for now. */
printf("Line one\n");
/* printf("Line two\n"); */
return 0;
}Line one
Multi-line comments cannot be nested: the first */ always ends the comment, so do not put one comment inside another.
Writing useful comments
A good comment says why, not what. The code already says what happens; the comment explains the reason or something that is not obvious.
x = x + 1; // add 1 to x (not useful: the code says this)
count = count + 1; // the header line is counted too (useful: explains a decision)Use comments to explain the purpose of a function, the meaning of a strange number, or a trick. Keep them up to date: a wrong comment is worse than none.
A comment at the top of a file
In larger programs it is common to start each file with a short block that says what the file is for, who wrote it and anything a reader must know before changing it. Functions often get a comment too, saying what they take, what they give back and what can go wrong:
/* area: the area of a rectangle.
width and height must not be negative. */
int area(int width, int height) {
return width * height;
}Such comments are read far more often than they are written, so a few clear sentences save a lot of time later.
Practice exercises
- Add a comment above each line of the Hello World program saying what it does.
- Switch off one
printfline with//, run the program, then switch it on again. - Put a
/* ... */comment inside another one and read the error the compiler gives.