Basic Syntax
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.
Program Structure
Every C program shares a fixed skeleton. No matter how complex the program gets, the core structure stays the same:
#include <stdio.h>
int main(void) {
return 0;
}
This is the smallest valid C program — it does nothing, but the structure is complete. Let's break it down:
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) |
The main Function
int main(void) {
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.
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).
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.
int age = 18;
age = age + 1;
printf("I am %d years old\n", age);
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:
int age = 18; age = age + 1; printf("%d\n", age);
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.
Code Blocks
A group of statements enclosed in curly braces {} forms a code block (also called a compound statement):
int main(void) {
int x = 10;
int y = 20;
int sum = x + y;
printf("Sum = %d\n", sum);
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:
int main(void) {
int a = 1;
{
int b = 2;
printf("a + b = %d\n", a + b);
}
return 0;
}
The inner block can access the outer a, but the outer block cannot access the inner b.
The printf Function
printf is the most commonly used output function in C. The name comes from print formatted.
Basic Usage
printf("Hello, World!\n");
The content inside the double quotes is called the format string and is printed as-is (except for escape characters).
Format Specifiers
The power of printf lies in formatting variable values for output:
int age = 18;
float height = 1.75f;
char grade = 'A';
printf("Age: %d\n", age);
printf("Height: %.2f\n", height);
printf("Grade: %c\n", grade);
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:
int a = 3, b = 4;
printf("%d + %d = %d\n", a, b, a + b);
Width and Alignment
printf("[%5d]\n", 42);
printf("[%-5d]\n", 42);
printf("[%05d]\n", 42);
[ 42]
[42 ]
[00042]
%5d— Minimum width 5, right-aligned%-5d— Minimum width 5, left-aligned%05d— Minimum width 5, zero-padded
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 |
printf("C:\\Users\\admin\\file.txt\n");
C:\Users\admin\file.txt
Comments
Comments are notes for humans — the compiler completely ignores them. Good comments make code easier to understand.
Single-Line Comments
C99 introduced // style single-line comments. Everything from // to the end of the line is a comment:
int score = 100;
Multi-Line Comments
/* */ style comments can span multiple lines:
/*
* This program calculates
* the sum of two numbers
*/
#include <stdio.h>
int main(void) {
int a = 10;
int b = 20;
printf("%d\n", a + b);
return 0;
}
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:
int max_retries = 3;
An unnecessary comment (the code already explains everything):
int x = 10;
/*
/* nested comment */
*/
The inner */ prematurely closes the outer comment, leaving the remaining */ as a syntax error.
Identifiers and Keywords
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)
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.
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:
#include <stdio.h>
int main(void) {
printf("=== Student Info ===\n");
printf("Name:\t%s\n", "Alice");
printf("Age:\t%d\n", 20);
printf("Score:\t%.1f\n", 95.5);
printf("Grade:\t%c\n", 'A');
printf("====================\n");
return 0;
}
=== 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
📖 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



