C Comments
The last lesson printed text to the screen. A comment is a note for the reader of the code, and the compiler ignores it.
Comment on its own line
This comment sits above the code it describes. The program prints the same line with or without it.
#include <stdio.h>
int main() {
// This program prints a greeting.
printf("Hello!\n");
return 0;
}Comment after code
A comment can follow code on one line. The code still runs, and the comment is ignored.
#include <stdio.h>
int main() {
printf("Hi\n"); // prints Hi
return 0;
}Comment over many lines
A comment between /* and */ can run over many lines. The compiler skips all of it.
#include <stdio.h>
int main() {
/* This comment
runs over two lines. */
printf("Done.\n");
return 0;
}Example
#include <stdio.h>
int main() {
// Print a greeting.
printf("Good morning.\n");
printf("Good afternoon.\n"); // second greeting
return 0;
}Key points
- A comment explains code for a human reader.
- Two slashes mark a comment that ends with the line.
- The pair /* and */ marks a comment that can run over many lines.
- The compiler skips comments when it builds the program.
- Comments never appear in the program output.
- A comment can stand alone on its own line or follow code on the same line.
Two greetings print in order. Both comments are ignored, so the output holds only the two greetings.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which two characters mark a comment that ends with the line?