Semantic Analysis in Compiler Design (original) (raw)

Last Updated : 11 Apr, 2026

Semantic Analysis is the third phase of a compiler, performed after syntax analysis. It ensures that a program is semantically correct, meaning it follows the logical rules of the programming language.

While syntax analysis checks the structure of the program, semantic analysis checks its meaning, such as correct use of variables, types, and expressions.

It works on the parse tree (or AST) and symbol table to:

During this phase, the syntax tree is enriched with type and scope information, forming an Annotated Syntax Tree, which is used in later stages like intermediate code generation.

Need

Even if a program is syntactically correct, it may still be incorrect logically.

**Example:

int a;
a = "hello"; // syntactically correct but semantically wrong

Syntax is valid, but type rules are violated.

Thus, semantic analysis ensures:

Role of Semantic Analyzer

The Semantic Analyzer performs the following major tasks:

Functions

1. Type Checking

Ensures that operands of operators are of compatible types.

**Example:

int x = 10;
float y = x + 2.5; // valid

**Invalid case:

int x = "abc"; // type mismatch

2. Scope Resolution

Determines the region in which a variable is accessible.

**Example:

{
int x = 10;
}
x = 20; // error: x out of scope

3. Type Conversion (Coercion)

Automatically converts data types when required.

**Example:

float x = 10.5;
float y = x * 2; // 2 → 2.0 (implicit conversion)

4. Function Checking

Ensures:

**Example:

int add(int a, int b);
add(5); // error: missing argument

5. Label Checking

Ensures that all labels used in the program are properly declared and referenced.

6. Flow Control Check

Ensures proper use of control flow statements.

Examples:

7. Symbol Table Handling

Semantic analysis uses the symbol table to:

Semantic Errors

Semantic errors are detected after syntax analysis. Common errors include:

1. Type Mismatch

int x = "hello";

2. Undeclared Variables

x = 10; // not declared

3. Multiple Declarations

int x;
int x; // redeclaration

4. Reserved Keyword Misuse

int while = 5;

5. Incorrect Function Usage

int add(int a, int b);
add(1); // wrong number of arguments

Static vs Dynamic Semantics

Static Semantics

Dynamic Semantics

**Examples:

Annotated Syntax Tree

During semantic analysis, additional information is added to the syntax tree.

**Example:

x = a + b;

After annotation:

This helps in intermediate code generation

Example of Semantic Analysis

float x = 10.1;
float y = x * 30;

Steps: