GATE / CS ARCHIVE

SUBJECT COLLECTION

Compiler Design · Lexical Analysis

11 questions, newest first

GATE CSE has asked 11 questions on Lexical Analysis (Compiler Design) from 1993 to 2026, in 9 of the 46 papers; the most recent is in GATE CSE 2026 Set 2. In the last five years it carried 0.4 marks per 100-mark paper on average, against 0.2 since 2003. Since 2014 the questions have been 2 MCQ, 1 MSQ and 1 NAT. 2 groups of questions here are solved the same way; “One per method” keeps the newest of each.

Browse topics
1 mark · MSQ
Report issue

Lexical and semantic errors in C

Lexical Analysis

Question 27, GATE 2026: Three declarations are considered: S1 begins char *str1 = "Hello; without a closing double quote; S2 is char *str2 = "Hello;"; and S3 is int *str3 = "Hello";. The options classify S1/S2 as lexical or syntactic errors and S3 as syntactic or semantic.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: C

Givens and goal

Three declarations are considered: S1 begins char *str1 = "Hello; without a closing double quote; S2 is char *str2 = "Hello;"; and S3 is int *str3 = "Hello";. The options classify S1/S2 as lexical or syntactic errors and S3 as syntactic or semantic.

Approach

Check whether valid tokens can be formed first, then whether the token sequence is grammatical, then whether the types are compatible.

Step-by-step solution

1. S1 opens a string literal but does not close it before the end of the line. Tokenization cannot form a valid string-literal token. In the compiler-phase classification used by the question, this is a lexical error.
2. S2 contains a properly closed string. Its semicolon inside the quotation marks is part of the string data, while the semicolon outside terminates the declaration. There is no lexical or syntactic error merely because both semicolons appear.
3. S3 has the shape of a grammatical declaration, but initializes an int pointer with a string literal, whose ordinary expression conversion produces a char pointer. The incompatible pointer types violate the C initialization constraints. This is a type/semantic error in the question's classification.
4. Therefore C correctly pairs the lexical error in S1 with the semantic error in S3. A and B misclassify S2, and D assigns the wrong compiler phase to S1.

Precision caveat: Real compilers may emit several cascading diagnostics after the malformed string. This solution classifies the primary defect, rather than treating every emitted diagnostic as a separate intended answer. In C, accepting a program after a warning or as an extension does not make a constraint violation valid standard C.

Phase distinction: lexical analysis groups characters into tokens, syntax checks token arrangements against the grammar, and semantic analysis checks constraints such as types. A semicolon character inside a valid string token has no role as a declaration terminator. That is why S2’s internal semicolon cannot by itself create a syntax error.

Original paper, page 21 · Answer key

1 mark · NAT
Report issue

Maximal-munch lexical tokens

Lexical Analysis

Question 35, GATE 2026: Identifiers are letter(letter|digit)*; numbers are digit+; whitespace is ignored. Letters are A-Z or a-z. Tokenize x1 23mm 78 y 7z zz5 14A 8H AaYcD and count non-whitespace tokens.
Tap to enlarge
Answer & solution

Official answer: 13

Givens and goal

Identifiers are letter(letter|digit)*; numbers are digit+; whitespace is ignored. Letters are A-Z or a-z. Tokenize x1 23mm 78 y 7z zz5 14A 8H AaYcD and count non-whitespace tokens.

Approach

At each position take the longest prefix matching a token definition.

Step-by-step solution

1. A letter-starting run can include later digits, so x1, zz5, and AaYcD are each a single identifier. A digit-starting run cannot be an identifier because the initial-letter condition fails.
2. Consequently 23mm splits as number 23 then identifier mm; 7z splits as 7 and z; 14A splits as 14 and A; 8H splits as 8 and H. Whitespace is a separator but is not required at every token boundary.
3. The full sequence is x1 | 23 | mm | 78 | y | 7 | z | zz5 | 14 | A | 8 | H | AaYcD. Numbering these items gives 13 non-whitespace tokens.
4. Equivalently the nine whitespace-separated chunks contribute 1+2+1+1+2+1+2+2+1=13. The answer follows the specified lexer definitions, not any additional rules a particular programming language might impose on malformed numeric literals.

Original paper, page 23 · Answer key

1 mark · MCQ
Report issue

Lexical Analysis

Question 19, GATE 2023: Identifiers match letter(letter|digit)*, with letter in A–Z or a–z and digit in 0–9. Choose the equivalent ε-NFA: A permits skipping the initial letter and then loops on letters/digits; B after the initial letter branches into an all-letter loop or an all-digit loop; C after the initial letter reaches an accepting hub, from which either a letter or digit branch can be selected by ε-transitions and returned to repeatedly; D after the initial letter repeats letter-then-digit pairs. The source diagrams are linked for exact state layouts.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

A valid identifier begins with one letter and then permits any mixture of letters and digits, including an empty suffix. In C the first letter reaches an accepting state; each repeated epsilon-selected letter/digit branch returns there through the outer epsilon edge. A wrongly accepts epsilon and leading digits; B forces the suffix to be all letters or all digits; D only permits letter-digit pairs after the first letter. Thus C.

Teaching detail. Test a candidate recognizer against boundary cases: a single letter must be accepted, an initial digit must be rejected, and the empty word must be rejected. Then test mixing in the suffix, such as a1b2. The accepting hub of C allows stopping immediately after the first letter and returning after each one-symbol suffix choice. An ε-transition changes state without consuming input; it does not allow an initial digit unless it bypasses the required initial-letter transition. These tests reveal why merely having letter and digit edges somewhere is insufficient.

Original paper, page 16 · Answer key

2 marks · MCQ
Report issue

Longest-prefix lexical analysis

Lexical Analysis

Question 37, GATE 2018: Tokens are T1=a?(b|c)*a, T2=b?(a|c)*b, T3=c?(b|a)*c, where ? is optional. Scan bbaacabc using longest-prefix matching. Choices A T1,T2,T3; B T1,T1,T3; C T2,T1,T3; D T3,T3.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Method

At the first position T1 can consume bba: its final a ends the token before the next a. T2 can consume bb but cannot include both leading b symbols in its middle (a|c)*. T3 consumes bbaac; it cannot consume the entire input because its middle cannot contain the earlier c. Remove that five-character prefix and rescan abc, which T3 consumes completely. Longest match is decided afresh at each position, rather than choosing the earliest token pattern that can match anything.

Solution

On bbaacabc, the longest first token is bbaac, matching T3=(optional c)(a|b)*c. T1 matches only bba and T2 only bb at that position. The remaining abc also matches T3 in full, longer than the alternatives. Therefore the output is T3, T3, D.

Original paper, page 15 · Answer key

1 mark · MCQ
Report issue

Compiler keyword recognition

Lexical Analysis

Question 1, GATE 2011: In a compiler, during which phase are language keywords recognized?

(A) Parsing the program
(B) Code generation
(C) Lexical analysis
(D) Dataflow analysis
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Lexical analysis groups source characters into tokens and recognizes reserved keywords, often by distinguishing them from identifier tokens using a keyword table. This precedes parsing, so C.

A scanner first isolates a lexeme such as 'while'. It then returns the reserved token WHILE rather than an ordinary identifier token. A parser consumes that token to determine grammatical structure. Code generation emits target instructions after the program has been analyzed, while dataflow analysis studies facts such as reaching definitions. These later tasks cannot be the first point at which the keyword token is recognized.

Original paper, page 2 · Answer key

1 mark · MCQ
Report issue

Automaton model for lexical analysis

Lexical Analysis

Question 19, GATE 2011: Which machine model has the necessary and sufficient power for conventional lexical analysis of a modern language such as Java?

(A) Finite-state automaton
(B) Deterministic pushdown automaton
(C) Nondeterministic pushdown automaton
(D) Turing machine
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Conventional token categories such as identifiers, keywords and numeric literals are specified by regular patterns. Finite-state automata suffice to recognize them; pushdown or Turing power is unnecessary for this lexical task. Hence A, distinguished from parsing nested syntax.

A lexical analyzer needs only a finite summary of a token prefix: for example, whether it has begun an identifier, is inside a number, or has just seen an exponent sign. A regular expression for a token can be converted to an NFA and then a DFA. Nested grammatical structure, such as matching arbitrary levels of parentheses, is handled later by parsing. Stronger machines could perform lexical recognition too, but their extra power is not necessary.

Original paper, page 5 · Answer key

1 mark · MCQ
Report issue

Lexical tokens in a printf statement

Lexical Analysis

Question 1.18, GATE 2000: Count tokens in the statement printf("i=%d, &i=%x", i, &i);. Choices:3,26,10,21.
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Step 1: The entire quoted format string is one string-literal token, regardless of its spaces, percent signs, commas or ampersand.

Step 2: The tokens are printf, (, the string literal, comma, i, comma, &, i, ), semicolon: ten in total.

Hence C. The count concerns lexical analysis, not characters or semantic correctness of the format specifier for a pointer; such a formatting issue does not split the string into more tokens.

Original paper, page 3

2 marks · MSQ
Report issue

Blank-insensitive FORTRAN tokenization

Lexical Analysis

Question 2.14, GATE 1999: Count tokens in legacy FORTRAN DO 10 I = 1.25. Options 3,4,5,none; the number contains a decimal point, not a comma.
Tap to enlarge
Select all that apply
Answer & solution

Answer: A: 3 (no official key was published)

In the classic fixed-form FORTRAN lexical convention, embedded blanks are insignificant outside literals. Thus DO 10 I becomes the identifier DO10I when the remainder is an assignment rather than a valid DO-loop header. The decimal point in 1.25 means this is not the loop form DO 10 I=1,25. Its tokens are identifier DO10I, assignment equals, and real literal 1.25: three, A.

Original paper, page 5

1 mark · MCQ
Report issue

Recognizing a Pascal token without lookahead

Lexical Analysis

Question 1.13, GATE 1995: Which can definitely be recognized as a whole token without reading the next character: I begin, II program, III <>?
Tap to enlarge
Your answer
Answer & solution

Answer: C: III (no official key was published)

The characters begin may be followed by another identifier character, producing an identifier such as beginning rather than the keyword begin. The same issue applies to program. The lexer therefore needs to determine the word boundary before deciding those tokens. Pascal’s <> is a complete relational operator with no longer operator having it as a prefix, so it can be recognized immediately after the second character. This is the longest-token principle, not a claim that keywords cannot ever be recognized.

Original paper, page 2

Descriptive
Report issue

Distinguish Pascal lexical and syntax errors

Lexical Analysis

Question 10(b), GATE 1995: Identify errors in: if A > 1, then B = 2.5A else read(C);
Tap to enlarge
Answer & solution

Answer: Remove the comma, use := for assignment, and replace the malformed/adjacent 2.5A with a valid expression such as 2.5*A if multiplication was intended. (no official key was published)

The comma after 1 is not allowed between an if condition and then. Delete it. The then branch needs a statement; B=... is a comparison expression, not Pascal assignment, so use B:=.... Neither comma nor = is an invalid token by itself: their placement/use is a syntactic error.

The character sequence 2.5A is not one valid Pascal numeric literal. A scanner may report an invalid numeric suffix, or tokenize it as the real literal 2.5 followed by identifier A, depending on its lexical rules. In the latter case the parser still rejects the adjacent operands because no operator connects them. Pascal has no implicit multiplication. If multiplication was intended, write 2.5*A; if the A was accidental, deleting it is a different possible repair.

Under the multiplication interpretation a corrected statement is “if A > 1 then B := 2.5*A else read(C);”. Whether assigning this real-valued expression to B is type-correct additionally depends on B’s declaration, which the question does not provide. Calling all three faults lexical is imprecise; the solution distinguishes token formation from grammar and typing.

Original paper, page 6

Report issue

FORTRAN77 keywords as identifiers

Lexical Analysis

Question 1.4, GATE 1993: Which fixed-form FORTRAN77 statements are valid: DO 13 I = 1; A = DIM ***7; READ = 15.0; GO TO 3 = 10?
Tap to enlarge
Select all that apply
Answer & solution

Answer: A,C,D as assignment statements (no official key was published)

FORTRAN77 does not reserve these apparent keywords, and blanks outside character constants do not distinguish tokens in fixed form. DO 13 I = 1 can therefore be an assignment to variable DO13I, not a DO loop. READ=15.0 assigns to variable READ, and GO TO 3=10 assigns to GOTO3. These names satisfy the traditional letter-first length rule. DIM***7 has an invalid triple-star operator and is not a valid exponentiation expression. The answer concerns statements placed in valid fixed-form source columns and with ordinary implicit typing, not modern free-form parsing.

Original paper, page 1