Computer Science and IT‹›⌂ 0:00 studied

Module 8 · 16 min read · Free chapter

Lexical analysis

In short

Lexical analysis is the first compiler phase. It groups characters into lexemes and returns tokens such as id, num and relop to the parser, dropping spaces and comments. Patterns are regular expressions turned into a DFA. The lexer takes the longest match, and on a tie the rule listed first, so x+++y reads as x ++ + y.

What are you preparing for? We show the practice and previous year questions of your exam.

Start from zero: how a reservation clerk reads your form

Think of a railway reservation counter. You hand over a filled form, and the clerk does not understand it all at once. First the clerk reads the letters as words and numbers: "Patna", "12309", "2 seats". Then the clerk checks that the words are in the right boxes, such as a train number in the train box and a date in the date box.

Next comes meaning. The form may be neatly filled and still make no sense, for example a train that does not stop at your station, or a date in the past. Only after all these checks does the clerk type the booking into the computer and print the ticket.

A compiler does the same job for a program. It reads characters and groups them into words called tokens, checks their order against the grammar, checks their meaning, and finally writes machine instructions. This chapter covers the first step, lexical analysis, which turns a stream of characters into a stream of tokens.

Why it matters. Every later phase of a compiler sees only tokens, never raw characters. If this first step is wrong, nothing after it can be right, and GATE asks every year how many tokens a piece of C code has.

The phases of a compiler

A compiler translates a program in a source language, such as C, into an equivalent program in a target language, usually machine code. It does this in six logical phases, and each phase hands its output to the next. Two helpers sit beside all of them: the symbol table, which stores information about every name, and the error handler, which reports mistakes.

Phase Input Output
Lexical analysis Characters Tokens
Syntax analysis (parsing) Tokens Parse tree or syntax tree
Semantic analysis Syntax tree Tree checked for types and declarations
Intermediate code generation Checked tree Three-address code
Code optimisation Intermediate code Better intermediate code
Code generation Intermediate code Target machine code

Follow one statement, total = price + tax * 18;, where all three names are float variables. The lexer produces seven tokens before the semicolon: an identifier, the assignment sign, an identifier, plus, an identifier, star and the number 18. The parser builds a tree in which * sits below +, because multiplication binds tighter, and the semantic analyser notices that 18 is an integer and inserts a conversion to float.

<id,1> <=> <id,2> <+> <id,3> <*> <num,18> <;>

t1 = inttofloat(18)
t2 = id3 * t1
t3 = id2 + t2
id1 = t3

The intermediate code above uses one operator per line. The optimiser sees that the conversion of a constant can be done at compile time and that t3 is only a copy, so it reduces the code to two lines: t1 = id3 * 18.0 and id1 = id2 + t1. The code generator then picks registers and machine instructions for these two lines.

The first four phases form the front end, or analysis part, which depends mainly on the source language. The last two form the back end, or synthesis part, which depends mainly on the target machine. Machine-independent optimisation on intermediate code is often counted with the front end, so treat the split as a guide rather than a law.

Because the front and back end meet at the intermediate code, mm languages and nn machines need only m+nm + n pieces instead of m×nm \times n full compilers. A compiler also works with other tools: the preprocessor expands #include and macros before compilation, the assembler turns assembly into object code, and the linker and loader join object files and place the program in memory.

Why it matters. Exam questions often ask which phase catches a given error, or which phase produces a given output. If you remember the table above, you can answer most of them in seconds.

Tokens, lexemes and patterns

Three words are used very precisely in this topic, so fix them now. A lexeme is the actual sequence of characters in the program, such as count1 or <= or 3.14. A token is the category the lexeme belongs to, passed to the parser as a pair of a token name and an attribute value. A pattern is the rule that describes every lexeme of a token.

Token Sample lexemes Pattern in words
id count1, rate, x A letter followed by letters or digits
num 0, 18, 3.14 One or more digits, with an optional fraction
if if The characters i and f exactly
relop <, <=, ==, !=, >, >= Any of the six comparison operators
literal "hello", "sum = %d" Anything between double quotes except a double quote

The attribute value carries the detail the parser does not need but later phases do. For an identifier it is a pointer to its symbol-table entry, so <id, 3> means "the name stored in row 3". For a number it is the value, and for relop it says which of the six operators was seen.

The usual token classes are keywords (int, while, return), identifiers, constants, string literals, operators (+, ++, &&) and punctuation (;, ,, (, ), {, }). Whitespace, newlines and comments also match patterns, but the lexer throws them away. That is why the parser never has to deal with spaces.

Why separate lexing from parsing at all? A grammar written over characters would be huge and slow to parse. Lexing with a fast automaton first makes the parser simpler, speeds up the compiler, and keeps character-set details in one place.

Why it matters. Questions on "which is a token and which is a lexeme" catch many students. Remember that the lexeme is what you see in the source, and the token is the label the parser sees.

From regular expressions to a lexer DFA

Patterns are written as regular expressions, which you have met in finite automata. To keep them readable, compilers use regular definitions, which give names to smaller expressions and then build on those names.

letter=a+b+⋯+z+A+⋯+Z+_\mathit{letter} = a + b + \dots + z + A + \dots + Z + \_
digit=0+1+⋯+9\mathit{digit} = 0 + 1 + \dots + 9
id=letter(letter+digit)∗\mathit{id} = \mathit{letter}(\mathit{letter} + \mathit{digit})^*
num=digit+(. digit++ε)\mathit{num} = \mathit{digit}^+ (.\,\mathit{digit}^+ + \varepsilon)

Here ++ between expressions means "or", ∗^* means "zero or more" and +^+ means "one or more". So rate2 is an identifier and 2rate is not, and 3.14 is a number while 3. is not.

A lexer generator turns such definitions into a program in three steps. First, each regular expression becomes a small NFA, and the NFAs are joined with ε-moves. Second, the subset construction turns the NFA into a DFA, where each DFA state is a set of NFA states. Third, the DFA is minimised by merging states that behave the same on every input.

The subset construction can, in the worst case, blow up an NFA with nn states into a DFA with 2n2^n states. In practice token patterns stay small, and a DFA reads each character in O(1)O(1) time. So a lexer runs in time proportional to the length of the input, which is the best possible.

Worked example. Build the minimal DFA for id\mathit{id}. State A is the start; on a letter it goes to state B, which accepts; from B, both letters and digits loop back to B. A digit from A goes to a dead state, so the minimal DFA has two useful states plus one dead state, three in all if the dead state is counted.

The relational operators need a hand-drawn transition diagram. From the start, < leads to a state that must look at one more character: = gives <=, > gives <> (not-equal in some languages), and anything else gives < with a retract, which pushes the extra character back. The states that retract are marked with a star in diagrams.

Why it matters. The same automata you study in theory of computation run inside every compiler. GATE sometimes asks for the number of states in the DFA of a token, and the subset construction is the tool for it.

Longest match, rule priority and input buffering

The input ifx = 1; starts with if, which matches the keyword, but ifx also matches the identifier pattern. Which token should the lexer return? Two rules settle every such case.

Rule 1: longest match (maximal munch). The lexer keeps reading as long as some pattern can still match, and returns the longest prefix that matches. So ifx is one identifier, <= is one token rather than < then =, and count123 is one identifier.

Rule 2: priority. If two patterns match the same longest prefix, the one listed first wins. The keyword if and the identifier pattern both match exactly if, so keywords are listed before identifiers. An alternative design stores keywords in the symbol table in advance and looks each identifier up.

Maximal munch gives answers that surprise people. The C input x+++y is read as x, ++, +, y, so it means (x++) + y. The input a---b is a, --, -, b, and x+++++y becomes x ++ ++ + y, which then fails in the parser even though x++ + ++y would have been legal.

To read characters fast, a lexer uses input buffering. The input is loaded into two halves of a buffer, each of size NN characters, and two pointers mark the current lexeme: lexemeBegin at its start and forward scanning ahead. When forward reaches the end of one half, the other half is refilled.

A sentinel, a special eof character placed at the end of each half, saves time. Without it, every character needs two tests, one for the buffer end and one for the character itself. With it, one test on the character is enough, and only when it sees eof does the lexer check which case it is in.

Lookahead is the number of extra characters read before deciding. Most C tokens need one character of lookahead, as with > versus >=. Some older languages needed far more, which is one reason modern languages reserve keywords and ignore nothing inside identifiers.

Why it matters. Maximal munch decides the token count in many GATE questions. A wrong split such as + + + instead of ++ + changes the answer.

The symbol table and lexical errors

When the lexer meets an identifier, it looks the name up in the symbol table and inserts it if it is new. The table then collects information from every phase. The parser and semantic analyser add the type and scope, and the code generator adds the storage offset.

Field Example for price Filled by
Lexeme price Lexical analyser
Type float Semantic analyser, from the declaration
Scope Local to main Parser or semantic analyser
Size and offset 4 bytes at offset 8 Storage allocation in the back end

Since lookups happen for every identifier, the table must be fast. A hash table gives O(1)O(1) average time per lookup and insert, while a linear list gives O(n)O(n) and a balanced search tree gives O(log⁡n)O(\log n) for nn names. For nested scopes, compilers keep one table per scope linked to the enclosing one, or a stack of scopes.

A lexical error happens when no pattern matches the next characters. Typical cases are an illegal character such as @ outside a string in C, a string with no closing quote, a comment that never ends, and an identifier longer than the allowed length. The lexer reports the line number, then tries to continue so that more errors can be found in one run.

The simplest recovery is panic mode: delete characters until one that can start a valid token is found. Other repairs are deleting one character, inserting a missing character, replacing a character, or swapping two neighbours. These repairs guess what the programmer meant, so they can cause later false errors.

Many mistakes are not lexical errors. The text fi (x > 0) contains a valid identifier fi, and the parser complains, not the lexer. Similarly int 2x; is split by maximal munch into the number 2 and the identifier x, both valid tokens, so again the parser reports the error.

Why it matters. Questions often list four mistakes and ask which one the lexer detects. The test is simple: can the characters be split into valid tokens at all?

Counting tokens in C: the GATE way

Token counting looks easy and still costs marks. Use one fixed method: rewrite the code with a space between tokens, applying maximal munch, then count. Drop every comment and every space, and keep each string literal whole.

Example 1. printf("sum = %d", a + b);. The tokens are printf, (, the whole literal "sum = %d", ,, a, +, b, ) and ;. That makes 9 tokens, and the spaces and %d inside the quotes do not add any.

Example 2. Count the tokens in this function.

int main() {
    int x = 10, *p = &x;   /* pointer to x */
    x++;
    return x >= 5 ? 1 : 0;
}

Line 1 gives int, main, (, ), {, which is 5. Line 2 gives int, x, =, 10, ,, *, p, =, &, x, ;, which is 11, and the comment adds nothing. Line 3 gives x, ++, ;, which is 3, line 4 gives return, x, >=, 5, ?, 1, :, 0, ;, which is 9, and line 5 gives }, which is 1.

5+11+3+9+1=29 tokens5 + 11 + 3 + 9 + 1 = 29 \text{ tokens}

Example 3. a = b+++c; splits as a, =, b, ++, +, c, ;, so it has 7 tokens. The tempting split b, +, ++, c is wrong, because the lexer takes the longest operator first.

Example 4. printf("/* not a comment */"); has 5 tokens: printf, (, the literal, ) and ;. Inside a string, comment marks are ordinary characters, and the reverse is also true: quotes inside a comment start no string.

Some details to settle before the exam. #include <stdio.h> is handled by the preprocessor, so most questions leave it out; read the question to see whether it counts. Character constants such as 'a' are one token, and ->, <<=, && and != are one token each.

Why it matters. A GATE token question has one right number, and a single wrong split loses the mark. A neat rewrite with spaces is the surest way to get it right.

Descriptive lens: how written papers ask this

Written papers for scientist and programmer posts, and university examinations, ask about this topic in four ways:

  1. Describe the phases of a compiler with a diagram, and trace one statement through all of them.
  2. Define and distinguish token, lexeme and pattern, with a table of examples.
  3. Construct a DFA or transition diagram for a given set of tokens, such as identifiers, numbers or relational operators.
  4. Explain design choices, such as why lexing is separated from parsing, or how sentinels speed up input buffering.

Practice questions (our own, not previous-year questions).

  1. Explain the phases of a compiler with a neat diagram. Show the output of each phase for the statement area = pi * r * r;. (15 marks)
  2. Distinguish between token, lexeme and pattern, giving two examples of each. Why is a symbol table needed, and which phases use it? (10 marks)
  3. Explain the longest-match and priority rules of a lexical analyser. How would the input ifcount<=10 be tokenised? (10 marks)

Answer plan for question 3.

  • Begin by stating that a lexer must choose one token when several patterns can match the remaining input.
  • State the longest-match rule: the lexer returns the longest prefix of the input that matches some pattern.
  • State the priority rule: when two patterns match the same longest prefix, the earlier listed pattern wins, so keywords are listed before identifiers.
  • Apply the rules to ifcount<=10, showing that ifcount is one identifier rather than the keyword if followed by count.
  • Continue the trace to show that <= is one relational operator, found with one character of lookahead, and that 10 is a number.
  • Conclude with the token stream id, relop and num, and add that the parser, not the lexer, decides whether this order is legal.

Quick revision

  • The six phases are lexical, syntax and semantic analysis, intermediate code generation, optimisation and code generation.
  • The front end depends on the source language, and the back end depends on the target machine.
  • A lexeme is the actual text, a token is its category with an attribute, and a pattern is the rule for the category.
  • Tokens are keywords, identifiers, constants, literals, operators and punctuation, while whitespace and comments are dropped.
  • Patterns are regular expressions, turned into an NFA, then a DFA by subset construction, then a minimal DFA.
  • Longest match comes first, and the earlier listed rule breaks ties, so keywords beat identifiers.
  • Two buffer halves with eof sentinels need one test per character.
  • The symbol table is usually a hash table with O(1)O(1) average lookup, and every phase uses it.
  • Only text that cannot be split into valid tokens is a lexical error.
  • A string literal is one token, a comment is zero tokens, and ++, <= and += are one token each.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 15 answered

  1. A missing semicolon at the end of a C statement is detected by the:

  2. Which phase belongs to the back end of a compiler?

  3. With a common intermediate code, compilers for mm languages on nn machines need how many front-end and back-end pieces?

  4. In the statement `int count = 5;`, `count` is a:

  5. Which of these produces no token?

  6. The identifier pattern letter(letter+digit)∗\mathit{letter}(\mathit{letter} + \mathit{digit})^* accepts which string?

  7. In the worst case, subset construction on an NFA with nn states gives a DFA with up to:

  8. By maximal munch, the C input `x+++y` is read as:

  9. Why are keyword patterns listed before the identifier pattern in a lexer specification?

  10. A sentinel at the end of each buffer half lets the lexer:

  11. The usual data structure for a symbol table, giving O(1)O(1) average lookup, is a:

  12. Which error is detected by the lexical analyser?

  13. How many tokens are in `printf("sum = %d", a + b);`?

  14. How many tokens are in `a = b+++c;`?

  15. Which data-flow analysis is named in the GATE 2026 CS syllabus under Compiler Design?

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

What is the difference between a token and a lexeme?

A lexeme is the actual text in the program, such as count. A token is its category, such as id, passed to the parser with an attribute.

How many tokens are in printf("sum = %d", a + b);?

There are 9 tokens: printf, (, the string literal, comma, a, +, b, ) and the semicolon. The whole string counts as one token.

Is a misspelt keyword a lexical error?

No. A word like fi is a valid identifier, so the lexer accepts it and the parser reports the error.

What is the longest match rule?

The lexer returns the longest prefix of the input that matches any pattern. So <= is one token, not < followed by =.

More in this module: Compiler design

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Compiler Design (IIT Kharagpur, 106105190): phases of a compiler and lexical analysis