
Simple C Program

Phases of Compiler

2. Syntax Analysis
Purpose: Ensures the code follows the rules of grammar.
Example: Checks if statements like sum = a + b;
are syntactically correct.
Output: A syntax tree or parse tree that represents the structure of the program.
3. Semantic Analysis
Purpose: Checks the meaning of the program.
Verifies that:
- Variables (
a
,b
,sum
) are declared before use. - Operations like
sum = a + b
are valid for the types of variables. - Detects errors like type mismatches or undeclared variables.
4. Intermediate Code Generation
Purpose: Transforms the code into an intermediate representation (IR), which is easier for the compiler to optimize.
Example IR for the program

5. Code Optimization
Purpose: Improves the efficiency of the intermediate code.
Example optimization:
Instead of separately assigning t1 = 5
and t2 = 3
, directly calculate t3 = 8
.
6. Code Generation
Purpose: Converts the optimized intermediate code into machine code (binary instructions).
Example machine code

This machine code is what the computer executes.
7. Symbol Table and Error Handling
A symbol table keeps track of variables (a
, b
, sum
), their types, and memory locations throughout all phases.
Error handling happens in phases like:
- Lexical Analysis: Invalid tokens or characters.
- Syntax Analysis: Grammar errors.
- Semantic Analysis: Logical errors or undeclared variables.
A compiler goes through 7 phases:
- Lexical Analysis
- Syntax Analysis
- Semantic Analysis
- Intermediate Code Generation
- Code Optimization
- Code Generation
- Symbol Table and Error Handling