C: Syntax: Structure and Semicolons
Learning C's basic syntax is like learning the strokes of Chinese characters — horizontal, vertical, left-fall, right-fall seem simple, but every beautiful piece of writing is built from them.
TL;DR: Every C program has the same skeleton: preprocessor directive,
mainfunction, braces, andreturn 0;. Statements end with semicolons, blocks use{}, output usesprintf, and comments use//or/* */. These five rules cover most beginner code.
1. Program Structure
Every C program shares a fixed skeleton. No matter how complex the program gets, the core structure stays the same:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Return result
return 0;
}
This is the smallest valid C program — it does nothing, but the structure is complete. Let's break it down:
(1) Preprocessor Directives
#include <stdio.h> is a preprocessor directive. It starts with # and is processed before compilation.
#include— Inserts the contents of the specified header file at this location<stdio.h>— The standard I/O header file, containing declarations forprintf,scanf, and other functions- Angle brackets
<>tell the preprocessor to search for the header in system directories
You'll encounter other common header files as well:
| Header | What It Provides |
|---|---|
<stdio.h> |
Input/output (printf, scanf) |
<stdlib.h> |
General utilities (malloc, exit) |
<math.h> |
Math functions (sqrt, sin) |
<string.h> |
String operations (strlen, strcpy) |
<ctype.h> |
Character classification (isdigit, toupper) |
(2) The main Function
// Function definition
int main(void) {
// Return result
return 0;
}
int— The function returns an integermain— The function name; C specifies that program execution begins at the main function(void)— An empty parameter list, meaning the function takes no arguments{ }— The function body, enclosed in curly bracesreturn 0— Returns 0 to indicate the program ended normally
main is the single entry point of a C program. You can only have one main function — the operating system calls it to start your program.
(3) Other Forms of main
You may see a different form of main in some textbooks:
int main(int argc, char *argv[])
This form can receive command-line arguments, which we'll cover in detail later. For now, int main(void) is all you need.
void main(). This is not standard C and some compilers will warn about it. Always use int main(void).
2. Statements and Semicolons
In C, the semicolon ; marks the end of a statement. Think of it like a period at the end of a sentence — just as a sentence needs a period, a statement needs a semicolon.
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int age = 18;
age = age + 1;
// I/O operation
printf("I am %d years old\n", age);
// Return result
return 0;
}
Each line is a statement, ending with a semicolon.
A common mistake — forgetting the semicolon:
int age = 18
The compiler doesn't recognize "line breaks" — it only recognizes semicolons. Theoretically, you could write all your code on one line:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) { int age = 18; age = age + 1; printf("%d\n", age); return 0; }
While syntactically legal, this is never recommended. Good coding style puts one statement per line.
;
It's useful in certain special cases (like an empty loop body), but you don't need to worry about that now.
3. Code Blocks
A group of statements enclosed in curly braces {} forms a code block (also called a compound statement):
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int x = 10;
// Variable declaration
int y = 20;
// Variable declaration
int sum = x + y;
// I/O operation
printf("Sum = %d\n", sum);
// Return result
return 0;
}
The entire main function body is one code block. Code blocks define scope — variables declared inside a block cannot be accessed outside it.
Code blocks can be nested:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int a = 1;
{
// Variable declaration
int b = 2;
// I/O operation
printf("a + b = %d\n", a + b);
}
// Return result
return 0;
}
The inner block can access the outer a, but the outer block cannot access the inner b.
4. The printf Function
printf is the most commonly used output function in C. The name comes from print formatted.
(1) Basic Usage
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// I/O operation
printf("Hello, World!\n");
// Return result
return 0;
}
The content inside the double quotes is called the format string and is printed as-is (except for escape characters).
(2) Format Specifiers
The power of printf lies in formatting variable values for output:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int age = 18;
// Variable declaration
float height = 1.75f;
// Variable declaration
char grade = 'A';
// I/O operation
printf("Age: %d\n", age);
// I/O operation
printf("Height: %.2f\n", height);
// I/O operation
printf("Grade: %c\n", grade);
// Return result
return 0;
}
Common format specifiers:
| Specifier | Type | Example Output |
|---|---|---|
%d |
int | 42 |
%f |
float / double | 3.140000 |
%.2f |
float (2 decimal places) | 3.14 |
%c |
char | A |
%s |
string | hello |
%ld |
long | 100000 |
%x |
hexadecimal integer | 2a |
%o |
octal integer | 52 |
%% |
literal percent sign | % |
printf — they correspond to the arguments in order:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int a = 3, b = 4;
// I/O operation
printf("%d + %d = %d\n", a, b, a + b);
// Return result
return 0;
}
(3) Width and Alignment
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// I/O operation
printf("[%5d]\n", 42);
// I/O operation
printf("[%-5d]\n", 42);
// I/O operation
printf("[%05d]\n", 42);
// Return result
return 0;
}
[ 42]
[42 ]
[00042]
%5d— Minimum width 5, right-aligned%-5d— Minimum width 5, left-aligned%05d— Minimum width 5, zero-padded
5. Escape Characters
Some characters can't be typed directly in a string (like newline or tab), so they're represented by escape characters starting with a backslash \:
| Escape | Meaning | Example |
|---|---|---|
\n |
Newline | printf("A\nB") prints A and B on separate lines |
\t |
Horizontal tab | Commonly used for aligned output |
\\ |
Literal backslash | To print \, write \\ |
\" |
Double quote | To print " inside a string |
\' |
Single quote | To print ' inside a character literal |
\0 |
Null character | Marks the end of a string |
\r |
Carriage return | Moves the cursor to the beginning of the line |
\b |
Backspace | Moves the cursor one position left |
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// I/O operation
printf("C:\\Users\\admin\\file.txt\n");
// Return result
return 0;
}
C:\Users\admin\file.txt
▶ Example: Escape Sequences in Action
▶ Try it YourselfLine one
Line two
Name Age
Path: C:\code\hello.c
Quote: "Hello"
\n breaks a line, \t adds a tab, \\ prints a backslash, and \" prints a quote.
6. Comments
Comments are notes for humans — the compiler completely ignores them. Good comments make code easier to understand.
(1) Single-Line Comments
C99 introduced // style single-line comments. Everything from // to the end of the line is a comment:
// A whole-line comment: the next line is the actual code
// Variable declaration
int score = 100; // Trailing comment: full marks
(2) Multi-Line Comments
/* */ style comments can span multiple lines:
/*
* This program calculates
* the sum of two numbers
*/
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int a = 10;
// Variable declaration
int b = 20;
// I/O operation
printf("%d\n", a + b);
// Return result
return 0;
}
(3) Comment Best Practices
Comments should explain why (the reasoning), not what (the obvious). The code itself already tells you what — comments should supplement with design intent and decisions that the code can't express.
A good comment:
// Variable declaration
int max_retries = 3; // Retry up to 3 times on transient network failures
An unnecessary comment (the code already explains everything):
// Variable declaration
int x = 10; // Assign 10 to x
/*
/* nested comment */
*/
The inner */ prematurely closes the outer comment, leaving the remaining */ as a syntax error.
▶ Example: Line, Block, and Trailing Comments
▶ Try it Yourselfarea = 12.57
Comments never reach the executable and do not affect performance; they are for humans and your future self.
7. Identifiers and Keywords
(1) Identifier Naming Rules
Identifiers are names you create yourself (variable names, function names, etc.). They must follow these rules:
- Can only contain letters (a-z, A-Z), digits (0-9), and underscores (_)
- Must start with a letter or underscore — cannot start with a digit
- Case-sensitive (
ageandAgeare different identifiers) - Cannot use C keywords
Legal names: age, student_name, _count, MAX_SIZE
Illegal names: 2name (starts with digit), my-age (contains hyphen), int (keyword)
(2) Naming Conventions
| Style | Format | Use Case | Example |
|---|---|---|---|
| snake_case | lowercase + underscores | Variable names, function names | student_count |
| UPPER_CASE | ALL CAPS + underscores | Constants | MAX_BUFFER_SIZE |
| CamelCase | Capitalize each word | Custom type names | StudentInfo |
C traditionally uses snake_case, unlike Java/C# which favor camelCase. The most important thing is consistency within a project.
(3) C99 Keywords
C99 has 37 keywords, all lowercase:
| Category | Keywords |
|---|---|
| Data Types | char short int long float double void signed unsigned _Bool _Complex _Imaginary |
| Control Flow | if else switch case default for while do break continue goto return |
| Storage Classes | auto extern static register typedef inline |
| Structures | struct union enum |
| Other | const volatile sizeof restrict |
You don't need to memorize these — they'll become second nature with practice. What matters is knowing that keywords cannot be used as identifiers.
▶ Example
Let's combine everything from this chapter into a program that demonstrates basic syntax:
▶ Try it Yourself=== Student Info ===
Name: Alice
Age: 20
Score: 95.5
Grade: A
====================
This program demonstrates: the #include preprocessor directive, the main function structure, printf formatted output, \n newline, \t tab alignment, and four common format specifiers (%d, %.1f, %c, %s).
❓ FAQ
if/for/while headers, and the brace before a function body do not take one. A missing semicolon usually reports expected ';'.if/for/while allow it, but always writing braces prevents scope bugs when you add a line later. Function bodies and struct definitions always need braces.puts prints a string and adds a newline; printf supports format specifiers such as %d, %.2f, and %s. Use printf for formatting and puts for plain strings.\\n (a literal backslash) or a string split across lines. C strings cannot span lines; use \n or a trailing backslash to continue.Main and MAIN are not main. C89 has 32 keywords, C99 adds 5, and later standards add more; keywords cannot be used as variable names.📖 Summary
- C program skeleton:
#includeheader +int main(void)function +return 0 - Semicolons mark the end of statements; every statement must end with one
- Curly braces
{}form code blocks and define variable scope - printf uses format specifiers to output different data types:
%d,%f,%c,%s - Escape characters start with
\:\nfor newline,\tfor tab,\\for a literal backslash
📝 Exercises
- Write a program that uses printf to display your own info card (name, age, hobby), using \t for alignment
- Write a program that uses a single printf call to output the following (using escape characters for newlines and tabs): Name Alice, Age 25, City London
- Intentionally write a nested multi-line comment in your code and observe the compiler's error message