C Syntax
Syntax is the set of rules that says how C code must be written, just as grammar says how sentences are written. The compiler is strict: a missing semicolon or bracket is enough to stop it. The good news is that the rules are few.
Statements and semicolons
A statement is one instruction, such as printing text or giving a variable a value. Each statement ends with a semicolon. Statements run one after the other, from top to bottom.
#include <stdio.h>
int main(void) {
printf("First\n");
printf("Second\n");
printf("Third\n");
return 0;
}First Second Third
Blocks
Curly braces { } group statements into a block. The body of main is a block, and later you will see blocks after if, for and while. Every { needs a matching }. Indenting the statements inside a block, usually by four spaces, does not change what the program does, but it makes the structure easy to see. Always indent.
Case sensitivity
C is case sensitive: printf and Printf are different names, and only printf exists. The same is true for your own names: total, Total and TOTAL are three different variables. Keywords of the language such as int, return and if are always written in lower case.
Whitespace
Spaces, tabs and line breaks between the parts of a statement do not matter to the compiler. These two programs do exactly the same thing:
#include <stdio.h>
int main(void){printf("Compact\n");return 0;}Compact
#include <stdio.h>
int main(void) {
printf("Readable\n");
return 0;
}Readable
The second one is much easier to read. Write code for people first: the compiler reads anything, your teammates and your future self do not.
Lines that start with #
Lines that begin with #, such as #include <stdio.h>, are not statements. They are instructions for the preprocessor, which runs before the compiler, and they do not end with a semicolon. You will learn more in the Preprocessor and Macros topic.
Practice exercises
- Write a program that prints three lines, then rewrite it so the whole program is on a single line. Check that the output is the same.
- Change
printftoPrintfand read the error. - Remove the closing
}ofmainand read the error. Where does the compiler say the problem is?