Practice free →
HomeGATE CSEcomputerscienceCompiler Design › How are RESERVED WORDS (keywords like 'if', 'whi…

How are RESERVED WORDS (keywords like 'if', 'while') typically handled by a scanner?

Athey are hard-coded into the scanner
Bscanned as identifiers, then matched in a table
Cthey are skipped by the scanner
Dthey generate errors and must be quoted
Answer & Solution
Correct answer: B. scanned as identifiers, then matched in a table
1. PROBLEM: keywords look like identifiers (sequences of letters/digits starting with a letter). 2. SOLUTION: scan the lexeme as if it were an identifier. THEN check if it matches a known keyword. 3. Implementation: a hash map of keyword strings to keyword token types. 4. If matched: emit the KEYWORD token (e.g. `WHILE`, `IF`). 5. If not matched: emit an IDENTIFIER token with the lexeme as the name. 6. This 'maximal munch then categorise' approach handles keywords with minimal scanner complexity. 7. Other options are not how real scanners work. _Source: Bob Nystrom, "Crafting Interpreters", Ch 4.7 (Reserved Words and Identifiers)._
Solve this in the app — GATE CSE practice & 24k+ MCQs →
Related questions