IAE Academy

GATE CS

Compiler phases and lexical analysis

A compiler translates source code in phases, and the first phase, lexical analysis, turns characters into tokens. Typical questions ask which phase does what, which phase reports which error, and how many tokens a C fragment has. Most of these are settled by the longest-match rule and by knowing what is and is not a token.

8 previous-year questions · 8 solved · 5 practice questions

Phases of a compiler

A compiler works in phases. Each phase reads the output of the one before it and produces a new representation of the program. The phases in order are lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimisation and code generation. Code optimisation is optional: a compiler can skip it and still produce correct code.

Phase

Input

Output

Lexical analysis

Stream of characters

Stream of tokens

Syntax analysis

Tokens

Parse tree or syntax tree

Semantic analysis

Syntax tree

Annotated syntax tree (types checked, names resolved)

Intermediate code generation

Annotated tree

Intermediate code, for example three-address code

Code optimisation

Intermediate code

Better intermediate code

Code generation

Intermediate code

Target (machine or assembly) code

The front end is the part that depends on the source language: lexical, syntax and semantic analysis and intermediate code generation. The back end is the part that depends on the target machine: code generation and the machine-dependent part of optimisation. Machine-independent optimisation works on the intermediate code and depends on neither. Intermediate code is the meeting point, so one front end can be paired with several back ends, and one back end with several front ends.

A pass is one reading of the whole program, in some representation. Several phases can be grouped into one pass. For example, the lexer, parser and semantic analyser often run together, with the parser asking the lexer for tokens one at a time.

Phase

Formal tool used

Lexical analysis

Regular expressions and finite automata

Syntax analysis

Context-free grammars and pushdown automata (parsers)

Semantic analysis

Type rules and syntax-directed definitions (attributes)

EXAM TIP

A phase takes the output of the previous phase as its input. The parser never sees characters or comments; it sees only tokens. Balanced parentheses are not a regular language, so the lexer cannot check them. That check belongs to the parser.

Symbol table and error detection

The symbol table is a data structure that stores information about names in the program: for each identifier its type, scope and where it is stored (such as its memory offset), and for a function its parameter types and return type. It is created and filled in the early phases: the lexical analyser may enter a lexeme, and later the parser and semantic analyser add attributes. Semantic analysis, optimisation and code generation read it. It is not itself a phase. Every phase also reports its errors through an error handler, and the lexer tracks line numbers so that messages can point to the source.

Kind of error

Detected in

Example

Lexical

Lexical analysis

Illegal character such as @ outside a string or comment in a C program; an unterminated string literal or comment

Syntax

Syntax analysis

Missing semicolon, unbalanced parentheses, if with no condition

Semantic

Semantic analysis

Undeclared variable, type mismatch, wrong number of arguments

EXAM TIP

Decide the phase by what is wrong. Characters that match no token pattern are a lexical error. A misspelled keyword or name that still forms a valid identifier is not lexical. A wrong order of tokens is syntactic. A correctly ordered statement that breaks a meaning rule (types, declarations) is semantic.

Tokens, lexemes and patterns

Lexical analysis is the only phase that reads the characters of the source. It groups them into meaningful units and removes comments and white space, which the later phases never see. It usually runs as a subroutine that the parser calls each time it needs the next token, and it enters identifiers in the symbol table.

Term

Meaning

Example

Token

A category name (with an optional attribute) passed to the parser

id, num, if, relop

Lexeme

The actual character sequence matched in the source

count, 3.14, if, <=

Pattern

The rule describing every lexeme of a token, usually a regular expression

letter followed by letters or digits, for id

A token such as id has many possible lexemes. A token such as if has just one lexeme. Tokens are usually the keywords, identifiers, constants, string literals, operators and punctuation symbols.

Regular definitions (a common convention)

  1. letter: any of a to z or A to Z, together with the underscore

  2. digit: any of 0 to 9

  3. id: letter followed by zero or more letters or digits

  4. number: one or more digits, optionally a fraction, optionally an exponent

  5. Keywords such as if, else, while are single fixed strings

Longest match and keyword priority

At each position the lexical analyser must decide which lexeme to take. Two rules decide it. Longest match (maximal munch): take the longest prefix of the remaining input that matches any pattern. Priority: if the longest match fits more than one pattern, the pattern listed first wins.

Keywords also match the identifier pattern. For example, if fits both. So the keyword rule is listed before the identifier rule. That choice gives if as a keyword, while iffy is still one identifier, because the identifier match is longer.

Input

Tokens by longest match

Count

a<=b

a, <=, b

3

x+++y

x, ++, +, y

4

x+++++y

x, ++, ++, +, y

5

ifx

ifx (one identifier)

1

12.5

12.5 (one number)

1

EXAM TIP

Longest match is greedy. At each position the lexer takes the longest match, whether or not the rest of the input can then be tokenised and whether or not the program parses. It never picks a shorter token to help later. In x+++++y it produces x, ++, ++, +, y, and the program is rejected later, even though x++ + ++y would have been valid.

Counting tokens in a C fragment

Procedure

  1. Ignore comments (both block and line) and white space. They are not tokens.

  2. Scan left to right, taking the longest match at each position.

  3. Count each keyword, identifier, constant, operator and punctuation symbol as one token. Operators made of several characters, such as ++, +=, >=, -> and <<=, are one token each.

  4. Count a whole string literal, including the quotes and any spaces inside it, as one token.

  5. Count a character constant such as 'a' as one token.

WORKED EXAMPLE

How many tokens are in this fragment?

int a = 5; /* set */ if (a >= 3) printf("hi %d", a);
Solution
  1. The comment is ignored.

  2. Statement 1: int, a, =, 5, ; gives 5 tokens.

  3. Statement 2 head: if, (, a, >=, 3, ) gives 6 tokens.

  4. Call: printf, (, "hi %d", ,, a, ), ; gives 7 tokens.

  5. Total: 5 + 6 + 7 = 18.

Answer: 18

EXAM TIP

The text inside a string literal is never split into tokens, and a comment may contain words that look like code, so ignore them as well.

Lexical errors and lexer generators

A lexical error occurs when no pattern matches the input at the current position, for example an illegal character or an unterminated string literal. Many mistakes still form valid tokens, so the lexer cannot catch them. A misspelled keyword such as whiel is a valid identifier. It is caught later only if the resulting token sequence breaks a syntax rule or a meaning rule.

Common recovery strategies

  1. Panic mode: delete characters from the remaining input until a valid token starts

  2. Delete one extra character

  3. Insert a missing character

  4. Replace one character by another

  5. Transpose two adjacent characters

A lexer generator takes a list of patterns (regular expressions) with an action for each, and produces a lexical analyser. Internally it builds a finite automaton for the patterns, typically an NFA converted to a DFA, and runs it with longest match and priority by order to choose the token.

PREVIOUS-YEAR QUESTIONS

8 questions from the CS papers

Try each question first, then open the answer. We placed each question under a topic ourselves; the exam paper does not label topics.

See these papers in full: GATE CSE 2026 Set 1 · GATE CSE 2026 Set 2 · GATE CSE 2025 Set 1 · GATE CSE 2024 Set 2 · GATE CSE 2023 · GATE CSE 2020 · GATE CSE 2018

GATE 2026 CS1 Q.27

GATE 2026 · CS1Q.27 · 1 mark · MSQ

Consider the following C statements:

char *str1 = "Hello;    /* Statement S1 */
char *str2 = "Hello;";  /* Statement S2 */
int *str3 = "Hello";    /* Statement S3 */

Which of the following options is/are correct?

  1. (A)

    S1 and S2 have syntactic errors

  2. (B)

    S2 has a lexical error and S3 has a syntactic error

  3. (C)

    S1 has a lexical error and S3 has a semantic error

  4. (D)

    S1 has a syntactic error and S3 has a semantic error

Answer and solution
See the question in the paper
GATE 2026 CS1 Q.27: answer and solution

GATE 2026 CS2 Q.35

GATE 2026 · CS2Q.35 · 1 mark · NAT

A lexical analyzer uses the following token definitions

For the string given below,

x1 23mm 78 y 7z zz5 14A 8H AaYcD

the number of tokens (excluding ) that will be produced by the lexical analyzer is ______. (answer in integer)

Answer and solution
See the question in the paper
GATE 2026 CS2 Q.35: answer and solution

GATE 2025 CS1 Q.12

GATE 2025 · CS1Q.12 · 1 mark · MCQ

Which ONE of the following statements is FALSE regarding the symbol table?

  1. (A)

    Symbol table is responsible for keeping track of the scope of variables.

  2. (B)

    Symbol table can be implemented using a binary search tree.

  3. (C)

    Symbol table is not required after the parsing phase.

  4. (D)

    Symbol table is created during the lexical analysis phase.

Answer and solution
See the question in the paper
GATE 2025 CS1 Q.12: answer and solution

GATE 2024 CS2 Q.21

GATE 2024 · CS2Q.21 · 1 mark · MCQ

Consider the following two sets:

Set X: P. Lexical Analyzer; Q. Syntax Analyzer; R. Intermediate Code Generator; S. Code Optimizer
Set Y: 1. Abstract Syntax Tree; 2. Token; 3. Parse Tree; 4. Constant Folding

Which one of the following options is the CORRECT match from Set X to Set Y ?

  1. (A)

    P – 4; Q – 1; R – 3; S – 2

  2. (B)

    P – 2; Q – 3; R – 1; S – 4

  3. (C)

    P – 2; Q – 1; R – 3; S – 4

  4. (D)

    P – 4; Q – 3; R – 2; S – 1

Answer and solution
See the question in the paper
GATE 2024 CS2 Q.21: answer and solution

GATE 2023 CS Q.11

GATE 2023 · CSQ.11 · 1 mark · MCQ

Consider the following statements regarding the front-end and back-end of a compiler.
S1: The front-end includes phases that are independent of the target hardware.
S2: The back-end includes phases that are specific to the target hardware.
S3: The back-end includes phases that are specific to the programming language used in the source code.
Identify the CORRECT option.

  1. (A)

    Only S1 is TRUE.

  2. (B)

    Only S1 and S2 are TRUE.

  3. (C)

    S1, S2, and S3 are all TRUE.

  4. (D)

    Only S1 and S3 are TRUE.

Answer and solution
See the question in the paper
GATE 2023 CS Q.11: answer and solution

GATE 2020 CS Q.9

GATE 2020 · CSQ.9 · 1 mark · MCQ

Consider the following statements.

I. Symbol table is accessed only during lexical analysis and syntax analysis.
II. Compilers for programming languages that support recursion necessarily need heap storage for memory allocation in the run-time environment.
III. Errors violating the condition 'any variable must be declared before its use' are detected during syntax analysis.

Which of the above statements is/are TRUE?

  1. (A)

    I only

  2. (B)

    I and III only

  3. (C)

    II only

  4. (D)

    None of I, II, and III

Answer and solution
See the question in the paper
GATE 2020 CS Q.9: answer and solution

GATE 2018 CS Q.8

GATE 2018 · CSQ.8 · 1 mark · MCQ

Which one of the following statements is FALSE?

  1. (A)

    Context-free grammar can be used to specify both lexical and syntax rules.

  2. (B)

    Type checking is done before parsing.

  3. (C)

    High-level language programs can be translated to different Intermediate Representations.

  4. (D)

    Arguments to a function can be passed using the program stack.

Answer and solution
See the question in the paper
GATE 2018 CS Q.8: answer and solution

GATE 2018 CS Q.37

GATE 2018 · CSQ.37 · 2 marks · MCQ

A lexical analyzer uses the following patterns to recognize three tokens , , and over the alphabet .

: a? (b|c)* a
: b? (a|c)* b
: c? (b|a)* c

Note that 'x?' means 0 or 1 occurrence of the symbol x. Note also that the analyzer outputs the token that matches the longest possible prefix.

If the string bbaacabc is processed by the analyzer, which one of the following is the sequence of tokens it outputs?

  1. (A)

  2. (B)

  3. (C)

  4. (D)

Answer and solution
See the question in the paper
GATE 2018 CS Q.37: answer and solution

OTHER EXAMS

ISRO: 3 questions

From ISRO's Scientist/Engineer written test: ISRO CS 2025, ISRO CS 2023. They are not counted in the GATE numbers on this page.

ISRO CS 2023 Q.7

ISRO 2023 · CSQ.7 · 1 mark · MCQ

Consider the NFA with epsilon-transitions below, which is meant to accept strings corresponding to a lexical token id. Here the token digit corresponds to the extended regular expression [0-9] and letter corresponds to [a-z A-Z]. In the diagram, a small incoming edge indicates a start state while a double circle indicates a final state.

Which of the following extended regular expressions corresponds to the token id?

ISRO CS 2023 question 7: An NFA with epsilon-transitions.Tap to open full size
Figure from the ISRO CS 2023 paper. It is part of the question.
Figure description

An NFA with epsilon-transitions. A start state (small incoming arrow from the left) has an edge labelled 'letter' to a double-circled final state F. From F, two epsilon edges leave: the upper one goes to a state from which an edge labelled 'letter' leads to another state, and the lower one goes to a state from which an edge labelled 'digit' leads to another state. Each of these two end states has an epsilon edge into a common join state at the right. From the join state a long epsilon edge, drawn as an arc over the top, returns to F.

  1. (A)

    letter (letter | digit)*

  2. (B)

    (letter | digit)* letter

  3. (C)

    (letter | digit)*

  4. (D)

    letter (letter* | digit*)

Answer and solution
ISRO CS 2023 Q.7: answer and solution

ISRO CS 2023 Q.10

ISRO 2023 · CSQ.10 · 1 mark · MCQ

Which sequence below best describes the order in which the phases of a compiler typically work?

  1. (A)

    Syntax analysis, lexical analysis, semantic analysis, code optimization, intermediate code generation

  2. (B)

    Lexical analysis, syntax analysis, semantic analysis, code optimization, intermediate code generation

  3. (C)

    Syntax analysis, lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization

  4. (D)

    Lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimization

Answer and solution
See the question in the paper
ISRO CS 2023 Q.10: answer and solution

PRACTICE

5 questions to test yourself

PRACTICE 11 mark · NAT

How many tokens does the C statement below contain? Assume the lexical analyser uses the longest-match rule.

x = y+++z;
Answer and solution

Answer:

  1. Scan left to right with longest match: x, =, y.

  2. At +++ the longest operator is ++, so the next token is ++.

  3. The remaining + is a token, then z, then ;.

  4. Tokens: x, =, y, ++, +, z, ; which is 7.

PRACTICE 21 mark · MCQ

In a C program, a variable is used without being declared. In which phase of the compiler is this error normally detected?

  1. (A)

    Lexical analysis

  2. (B)

    Syntax analysis

  3. (C)

    Semantic analysis

  4. (D)

    Code generation

Answer and solution

Answer: (C)

  1. The statement uses valid tokens in a valid order, so lexical and syntax analysis accept it.

  2. Checking that a name is declared needs the symbol table, which is a semantic check.

  3. The answer is C.

PRACTICE 32 marks · MSQ

Which of the following statements are correct?

  1. (A)

    For the input a<=b, a lexical analyser using longest match produces three tokens.

  2. (B)

    A missing closing parenthesis is normally reported by the lexical analyser.

  3. (C)

    A type mismatch, such as assigning a string literal to an int variable, is normally detected by type checking during semantic analysis.

  4. (D)

    White space between two tokens is passed to the parser as a separate token.

Answer and solution

Answer: (A), (C)

  1. A is true: the tokens are a, <=, b.

  2. B is false: unbalanced parentheses are a syntax error found by the parser.

  3. C is true: a type mismatch is a semantic error found by type checking.

  4. D is false: white space is discarded by the lexical analyser.

  5. The correct options are A and C.

PRACTICE 42 marks · NAT

How many tokens does the following C fragment contain?

for (i = 0; i < 10; i++) /* loop */
    s += a[i]; // add
Answer and solution

Answer:

  1. Comments are ignored.

  2. for, (, i, =, 0, ; gives 6 tokens.

  3. i, <, 10, ; gives 4 tokens, total 10.

  4. i, ++, ) gives 3 tokens, total 13.

  5. s, +=, a, [, i, ], ; gives 7 tokens (+= is one token).

  6. Total: 13 + 7 = 20.

PRACTICE 52 marks · MCQ

A lexical analyser has three patterns, listed in this order: R1 = a+, R2 = a+b, R3 = b. It applies longest match, and priority by order for ties. How many tokens does it produce for the input aaabaa?

  1. (A)

    2

  2. (B)

    3

  3. (C)

    4

  4. (D)

    6

Answer and solution

Answer: (A)

  1. At the first character, R1 matches aaa (3 characters) and R2 matches aaab (4 characters). The longest is R2, so the first token is aaab.

  2. The remaining input is aa. R1 matches aa, and R2 and R3 do not match.

  3. There are 2 tokens, so the answer is A.

OFFICIAL GATE 2027 SYLLABUS WORDING

Copied from the GATE 2027 syllabus; see all 2027 syllabi.

GATE CS

Lexical analysis

Preparing in Kolkata? IAE Academy's course for GATE CSE.