Statements & Semicolons
A C program is built out of statements — individual instructions that tell the computer to do something: compute a value, call a function, make a decision, repeat a block of code. Almost every statement in C ends with a semicolon ;. The semicolon isn't decoration — it's how the compiler knows where one statement ends and the next begins.
The classic "missing semicolon" error
Forgetting a semicolon is probably the single most common mistake every C beginner makes, and the compiler's error message can be confusing at first because it usually points at the next line, not the one that's actually missing the semicolon:
#include <stdio.h>
int main(void) {
int total = 10 // <-- missing semicolon here
printf("%d\n", total);
return 0;
}What counts as a statement
Most lines of C code you write are one of these kinds of statements:
Expression statements — an expression followed by a semicolon, like
total = total + 1;orprintf("hi");. The expression is evaluated and its result (if any) is discarded.Declaration statements — introduce a new variable, like
int count = 0;.Control-flow statements —
if,for,while,switch,return,break,continue,goto.Compound statements (blocks) — a sequence of statements wrapped in
{ }, which itself counts as a single statement wherever a statement is expected.
The empty statement
A lone semicolon ; is itself a valid statement — the empty statement. It does nothing. This is occasionally useful, most often as the body of a loop that does all of its work in the loop header itself:
/* Skip characters until we hit a newline or the end of the string. */
while (*p != '\n' && *p != '\0') {
p++;
}
/* The same idea written with an empty statement as the loop body. */
while (*p != '\n' && *p != '\0')
;
p++; /* still needs to advance past the character that stopped the loop */if (count > MAX_ALLOWED); /* <-- oops, empty statement! */
{
printf("Too many items!\n"); /* this block always runs */
}Compound statements and blocks
if (score >= 90) {
grade = 'A';
printf("Excellent!\n");
} /* no semicolon needed here */
struct Point {
int x;
int y;
}; /* semicolon required here — this is a declaration */