C Comments
Comments are notes you leave inside your code for humans to read. The compiler ignores them completely, so they are a safe place to explain what your program does.
As programs grow, it helps to explain why the code does what it does. Comments let you write those explanations directly in the file without changing how the program runs.
Single-Line Comments
A single-line comment starts with two slashes. Everything from the slashes to the end of that line is ignored by the compiler.
A single-line comment
#include <stdio.h>
int main() {
// This line prints a greeting
printf("Hello, World!");
return 0;
}Multi-Line Comments
When a note spans several lines, you can wrap it between /* and */. Everything between those markers is ignored, no matter how many lines it covers.
A multi-line comment
#include <stdio.h>
int main() {
/* This program prints a
message to the screen.
Written while learning C. */
printf("Comments are helpful");
return 0;
}- Use comments to explain why you did something, not just what the code says.
- You can place a comment at the end of a line of code to describe it.
- Comments are also handy for temporarily turning off a line while you test.
- Do not overdo it; clear code often needs fewer comments than messy code.
Note: You cannot place one /* */ comment inside another. The first */ ends the comment, even if you meant it to continue.
Note: If a line of code is causing trouble, put // in front of it to disable it without deleting it. This is a quick way to test what a line was doing.
Exercise: C Comments
Which symbol starts a single-line comment in C?