C Syntax

Syntax is the set of rules that decides whether your C code is written correctly. Learning the shape of a C program early makes every later topic easier.

Every C program follows the same basic structure. Once you can recognize the pieces, you will be able to read almost any small C program even before you understand every detail.

The standard structure

#include <stdio.h>

int main() {
    printf("Hello, World!");
    return 0;
}

Breaking It Down

LineWhat it does
#include <stdio.h>Loads the standard input/output library so you can use printf
int main()The main function, where the program starts running
{ }Curly braces group the statements that belong to main
printf(...)Prints text to the screen
return 0;Tells the system the program finished without errors

Statements and Semicolons

In C, most instructions are called statements, and every statement ends with a semicolon. Forgetting the semicolon is the most common beginner mistake and will stop your program from compiling.

Several statements

#include <stdio.h>

int main() {
    printf("Line one");
    printf("Line two");
    return 0;
}
  • C is case sensitive, so main and Main are not the same.
  • Statements run in order, from top to bottom.
  • Whitespace and blank lines are ignored, so use them to keep code readable.
  • Every opening brace { must have a matching closing brace }.
Note: The return 0; line uses the number zero to mean success. A different number would signal that something went wrong.
Note: If the compiler reports an error on a certain line, also check the line just above it. A missing semicolon is often noticed one line later than where it belongs.

Exercise: C Syntax

What must appear at the end of most C statements?