C Syntax
C syntax is the set of rules that decides how a C program must be written. Once you understand the basic structure of a C program, every other lesson builds on it.
Structure of a C Program
#include <stdio.h> // 1. include a header file
int main(void) { // 2. the main function
printf("Line one\n"); // 3. statements
printf("Line two\n");
return 0; // 4. return a status code
}Line one Line two
Syntax Rules to Remember
- Every statement ends with a semicolon (;).
- Curly braces { } group statements into a block, such as the body of a function.
- C is case-sensitive: printf and Printf are different names.
- Whitespace and indentation are ignored by the compiler but make code readable.
- Program execution always starts in main.
C Comments
Comments are notes for humans that the compiler ignores. C has single-line comments starting with // and multi-line comments between /* and */.
#include <stdio.h>
/* This program prints
a short greeting. */
int main(void) {
// print a message
printf("Comments are ignored\n");
return 0;
}Comments are ignored
Escape Sequences
Inside a string, a backslash starts an escape sequence: \n is a newline, \t is a tab, \" is a double quote and \\ is a backslash.
#include <stdio.h>
int main(void) {
printf("Name:\tAli\n");
printf("He said \"hi\"\n");
return 0;
}Name: Ali He said "hi"
Frequently asked questions
Why does C need semicolons?
The semicolon marks the end of a statement. Because C ignores line breaks, the compiler needs the semicolon to know where one statement stops and the next begins.
What is the difference between int main() and int main(void)?
In C, int main(void) explicitly says main takes no arguments. Before C23, empty parentheses meant "unspecified arguments", so (void) is the more precise style.
What does #include <stdio.h> do?
It tells the preprocessor to insert the standard input/output header, which declares functions like printf and scanf so your program can use them.