Lab viva guide

Compiler design viva questions and answers: 66 short answers on LEX, YACC, parsing and code optimisation

26 min read Updated English

Compiler design viva questions begin with your LEX or YACC program and then walk through the phases of a compiler: tokens, grammars, parsing tables, intermediate code and optimisation. This page gives 66 compiler design viva questions with short, exam-ready answers, grouped phase by phase (basics, lexical analysis and LEX, grammars and top-down parsing, bottom-up parsing and YACC, semantic analysis and intermediate code, optimisation, code generation and run-time environments), plus a parser comparison table, the mistakes examiners catch and a plan for the night before the CD lab exam.

How the examiner runs a compiler design lab viva

A compiler design lab usually has LEX programs that count words, lines, vowels or identifiers, recognise keywords and comments, or tokenise a small C program; YACC programs that validate an arithmetic expression, a variable name or a grammar such as a to the n b to the n and evaluate expressions; and C programs that compute FIRST and FOLLOW sets, build a predictive parsing table, run a shift-reduce parser, generate three-address code or apply simple optimisations. The viva follows the same order as the phases of a compiler.

  • First, your program: 'what does yytext hold?', 'why is yywrap returning 1?', 'how does YACC get tokens from LEX?'
  • Then the phase: 'which phase of the compiler does your program belong to, and what does that phase output?'
  • Then a small exercise: FIRST and FOLLOW of a grammar, remove left recursion, or write three-address code for an expression.
  • Then a comparison: compiler versus interpreter, top-down versus bottom-up, SLR versus LALR versus CLR.
  • Then optimisation: name and explain two machine-independent optimisations with an example.

Place everything in a phase

Whenever you explain a program or a term, say which phase it belongs to and what that phase hands to the next one: lexical analysis gives tokens, syntax analysis gives a parse tree, intermediate code generation gives three-address code. Examiners reward that map more than isolated definitions.

Compiler basics and phases

What is a compiler?

A compiler is a program that translates a whole source program written in a high-level language into an equivalent program in a target language, usually machine code or assembly, and reports errors it finds. The translated program can then run many times without the compiler, as gcc does for C.

What is the difference between a compiler and an interpreter?

A compiler translates the entire program first and produces a separate target program, so execution is fast and errors are reported together before running. An interpreter translates and executes statement by statement without a separate target file, so it starts quickly and is easy to debug, but runs slower. Java combines both: javac compiles to bytecode and the JVM interprets or JIT-compiles it.

Name the phases of a compiler.

Lexical analysis, syntax analysis, semantic analysis, intermediate code generation, code optimisation and code generation. The first three form the analysis part, or front end, and the last three the synthesis part, or back end. The symbol table manager and the error handler interact with every phase.

What is the role of the symbol table?

The symbol table stores information about every identifier in the program: its name, type, scope, storage size and location, and for functions their parameters. The lexical analyser or parser enters names, semantic analysis uses the types for checking, and code generation uses the addresses. It is usually implemented as a hash table for fast lookup.

What is the difference between a pass and a phase?

A phase is a logical step of compilation, like lexical analysis. A pass is one complete reading of the source program or its intermediate form. Several phases can be grouped into one pass; a one-pass compiler does all of them in a single reading, while multi-pass compilers allow better optimisation and use less memory per pass.

What are a preprocessor, assembler, linker and loader?

The preprocessor handles macros and file inclusion before compilation. The compiler produces assembly, which the assembler turns into relocatable object code. The linker combines object files and library code and resolves external references into one executable. The loader places the executable in memory, adjusts addresses and starts it.

What is a cross compiler?

A cross compiler runs on one machine but generates code for a different machine. Compilers that run on a laptop and produce code for an ARM microcontroller in an embedded board are cross compilers, because the target cannot comfortably host the compiler itself.

What is bootstrapping?

Bootstrapping means writing a compiler in the language it compiles. A small compiler for a subset of the language is written in another language or assembly, then used to compile a fuller compiler written in the subset, and so on. It is often shown with T-diagrams, which give the source, target and implementation language.

What is the front end and back end of a compiler, and why separate them?

The front end, lexical to intermediate code, depends on the source language. The back end, optimisation and code generation, depends on the target machine. Separating them through a common intermediate representation lets one front end serve many machines and one back end serve many languages, which is how GCC and LLVM are organised.

Lexical analysis and LEX

What does the lexical analyser do?

It reads the source characters, groups them into lexemes and outputs a token for each, such as keyword, identifier, number or operator. It also removes white space and comments, counts lines for error messages, and enters identifiers into the symbol table. It is usually called by the parser whenever the parser needs the next token.

What is the difference between a token, a lexeme and a pattern?

A token is the category name, such as id or num. A lexeme is the actual character sequence in the source that matches, such as count or 42. A pattern is the rule that describes the lexemes of a token, usually a regular expression, such as a letter followed by letters or digits for identifiers.

Count the tokens in the statement int a equals b plus 10 semicolon.

There are seven tokens: the keyword int, the identifier a, the operator equals, the identifier b, the operator plus, the number 10 and the semicolon. White space separates them but is not a token.

Why is lexical analysis separated from parsing?

It keeps the parser simpler, because the grammar deals with tokens instead of characters. It improves efficiency, since reading characters with buffering is the slowest part and can be specialised. And it improves portability, since character-set and input quirks stay inside the lexer.

What is input buffering, and what are sentinels?

The lexer reads the source in large blocks into a buffer with two pointers, one at the start of the lexeme and one moving ahead to find its end. A two-buffer scheme reloads one half while scanning the other. A sentinel, an end-of-file character at the end of each half, avoids testing for the buffer end on every character.

How are regular expressions and finite automata related to lexical analysis?

Token patterns are written as regular expressions. Each regular expression can be converted to a non-deterministic finite automaton by Thompson's construction, then to a deterministic one by subset construction, and minimised. The lexer runs that DFA over the input, which is exactly what LEX generates for us.

What is the difference between an NFA and a DFA?

In a DFA each state has exactly one transition for each input symbol and no epsilon moves, so recognition is one table lookup per character. An NFA may have several transitions or epsilon moves for a symbol. Both recognise the same class of languages, the regular languages, but a DFA can have exponentially more states.

What is the structure of a LEX program?

Three sections separated by double percent lines: the definitions section, with C declarations inside percent braces and named patterns; the rules section, with pairs of a regular expression and a C action; and the user subroutines section, with main and helper functions. LEX converts it into lex.yy.c, which we compile with cc.

What are yytext, yyleng, yylex and yywrap?

yytext points to the text of the current lexeme and yyleng is its length. yylex is the generated scanner function; each call returns the next token to the caller. yywrap is called at end of input; returning 1 tells the scanner to stop, and returning 0 means another input file has been set up.

How does LEX resolve a conflict when two patterns match?

It prefers the longest match, so 'ifcount' is read as one identifier rather than the keyword if followed by count. If two patterns match the same length, the rule listed first wins, which is why keyword rules are written before the general identifier rule.

What kinds of errors does the lexical analyser detect?

Only errors in forming tokens: an illegal character such as a stray at-sign in C, an unterminated string or comment, or an identifier or number that exceeds a length limit. Recovery is usually panic mode: delete characters until a valid token can start.

Grammars and top-down parsing

What is a context-free grammar?

A context-free grammar has a set of terminals, a set of non-terminals, a start symbol and productions where the left side is a single non-terminal. It describes the syntax of programming languages, such as nested expressions and blocks, which regular expressions cannot describe because they cannot count matching brackets.

What is a derivation and a parse tree?

A derivation is a sequence of production applications that rewrites the start symbol into a string of terminals. A leftmost derivation always replaces the leftmost non-terminal, a rightmost the rightmost. A parse tree shows the derivation graphically, with the start symbol at the root and the terminals at the leaves.

What is an ambiguous grammar?

A grammar is ambiguous if some string has more than one parse tree, or more than one leftmost derivation. E goes to E plus E, E star E or id is ambiguous: id plus id times id has two trees with different meanings. We remove ambiguity by encoding precedence and associativity in separate non-terminals for expressions, terms and factors.

What is left recursion, and how is it removed?

A grammar is left recursive if a non-terminal A can derive a string starting with A itself, as in A goes to A alpha or beta. Top-down parsers loop forever on it. We rewrite it as A goes to beta A-prime, and A-prime goes to alpha A-prime or epsilon, which generates the same strings without left recursion.

What is left factoring?

When two productions of a non-terminal begin with the same prefix, as in S goes to if E then S else S or if E then S, a predictive parser cannot choose. Left factoring takes the common prefix out: S goes to if E then S S-prime, and S-prime goes to else S or epsilon, deferring the choice until the parser has seen more input.

What is a top-down parser?

A top-down parser builds the parse tree from the root down to the leaves, trying to find a leftmost derivation of the input. Recursive descent and predictive LL(1) parsers are top-down. They need a grammar without left recursion and, for predictive parsing, left-factored.

What is recursive descent parsing?

It is a top-down method with one procedure for each non-terminal; the procedure matches the right side of a production by calling procedures for non-terminals and matching terminals. With backtracking it can try alternatives; a predictive recursive descent parser chooses the production by looking at the next token, with no backtracking.

How do you compute FIRST of a symbol?

FIRST of a terminal is the terminal itself. For a non-terminal X, for each production X goes to Y1 Y2 and so on, add FIRST of Y1 without epsilon; if Y1 can derive epsilon, add FIRST of Y2, and continue. If all of them can derive epsilon, or X has an epsilon production, add epsilon to FIRST of X.

How do you compute FOLLOW of a non-terminal?

Put the end marker, dollar, in FOLLOW of the start symbol. For a production A goes to alpha B beta, add FIRST of beta, without epsilon, to FOLLOW of B. If beta can derive epsilon, or B is at the end of the production, add everything in FOLLOW of A to FOLLOW of B. Repeat until nothing changes.

What is an LL(1) grammar?

LL(1) means the input is scanned Left to right, a Leftmost derivation is built, and 1 token of lookahead decides each step. A grammar is LL(1) if its predictive parsing table has at most one production in every cell. Ambiguous or left-recursive grammars are never LL(1).

How is the predictive parsing table built?

For each production A goes to alpha, put it in cell A, a for every terminal a in FIRST of alpha. If alpha can derive epsilon, also put it in cell A, b for every b in FOLLOW of A, including dollar. Empty cells are errors. If any cell gets two entries, the grammar is not LL(1).

Bottom-up parsing and YACC

What is bottom-up parsing?

A bottom-up parser builds the parse tree from the leaves up to the root, reducing the input string to the start symbol. It traces a rightmost derivation in reverse. Shift-reduce parsers, operator precedence parsers and the LR family, LR(0), SLR, LALR and CLR, are bottom-up.

What is a handle?

A handle is a substring that matches the right side of a production and whose reduction to the left side is one step of the reverse rightmost derivation. A shift-reduce parser repeatedly finds the handle at the top of its stack and reduces it; reducing a matching substring that is not the handle leads to a dead end.

Explain shift-reduce parsing.

The parser uses a stack and the input buffer. It shifts input symbols onto the stack until a handle appears on top, then reduces it to the production's left side. It accepts when the stack holds only the start symbol and the input is empty, and reports an error when no action applies. The four actions are shift, reduce, accept and error.

What are shift-reduce and reduce-reduce conflicts?

In a shift-reduce conflict the parser cannot decide whether to shift the next token or reduce the handle on the stack; the dangling else causes one. In a reduce-reduce conflict two productions could be used for the reduction. A grammar with conflicts in its table is not in that LR class; YACC reports conflicts and resolves them by default rules.

What is an LR parser, and why is it powerful?

LR means Left-to-right scan and Rightmost derivation in reverse. An LR parser uses a stack of states and a table with ACTION and GOTO parts. It handles nearly every programming language construct written as a context-free grammar, detects errors as early as possible, and its class of grammars is larger than LL.

What is the difference between LR(0) items and LR(1) items?

An LR(0) item is a production with a dot showing how much of it has been seen, such as A goes to X dot Y. An LR(1) item adds a lookahead terminal, saying which token may follow when this production is reduced. The lookahead lets CLR parsers reduce only where it is actually valid.

Compare SLR, CLR and LALR parsers.

SLR builds states from LR(0) items and reduces on all of FOLLOW of the left side, so it is simplest but weakest. CLR, or canonical LR(1), uses LR(1) items and is the most powerful, with many more states. LALR merges CLR states with the same core, giving SLR-sized tables with nearly CLR power; YACC and Bison generate LALR parsers.

Can merging states in LALR create conflicts?

Merging LR(1) states with the same core cannot create a new shift-reduce conflict, because shift actions depend only on the core. It can create a reduce-reduce conflict when merged states had different lookaheads for different reductions; in that case the grammar is LR(1) but not LALR(1).

What is an operator precedence parser?

It is a simple bottom-up parser for operator grammars, where no production has two adjacent non-terminals or an epsilon right side. It uses precedence relations, less than, equal and greater than, between terminals to find the handle. It suits arithmetic expressions but handles only a small class of grammars.

What is the structure of a YACC program?

Like LEX, three sections separated by double percent: declarations, with C code in percent braces and token declarations such as percent token NUMBER; the grammar rules with C actions in braces; and supporting C functions such as main and yyerror. YACC produces y.tab.c with the parser function yyparse, and with the d option, y.tab.h for token codes.

How do LEX and YACC work together?

YACC's yyparse calls yylex whenever it needs the next token. The LEX file includes y.tab.h so both agree on token numbers, and returns those tokens from its actions. A token's value, such as the number's integer value, is passed through the variable yylval. We compile lex.yy.c and y.tab.c together into one program.

What do dollar-dollar and dollar-1 mean in YACC actions?

Dollar-dollar is the semantic value of the left side of the rule being reduced, and dollar-1, dollar-2 and so on are the values of the first, second and later symbols on the right side. In E colon E plus T, the action dollar-dollar equals dollar-1 plus dollar-3 computes the sum in my calculator program.

How are precedence and associativity given in YACC?

With percent left, percent right and percent nonassoc declarations in the first section. Lines written later have higher precedence, so percent left plus minus followed by percent left star slash gives multiplication higher precedence. These declarations resolve the shift-reduce conflicts of an ambiguous expression grammar.

Semantic analysis and intermediate code

What does semantic analysis check?

It checks meaning that the grammar cannot express: that variables are declared before use, types match in expressions and assignments, functions are called with the right number and types of arguments, and break appears only inside a loop. It annotates the tree with types and inserts conversions, such as int to float.

What is a syntax-directed definition?

A syntax-directed definition attaches attributes to grammar symbols and semantic rules to productions that compute them. For E goes to E1 plus T, the rule E.val equals E1.val plus T.val computes the value of the expression. A syntax-directed translation scheme embeds the actions inside the productions at specific points.

What is the difference between synthesised and inherited attributes?

A synthesised attribute of a node is computed from the attributes of its children, so information flows up the tree, like the value of an expression. An inherited attribute is computed from the parent or siblings, so information flows down or across, like passing a declared type to each variable in a declaration list.

What are S-attributed and L-attributed definitions?

An S-attributed definition uses only synthesised attributes, so it can be evaluated during bottom-up parsing, as YACC does. An L-attributed definition allows inherited attributes that depend only on the parent and on siblings to the left, so it can be evaluated in one left-to-right depth-first pass, suiting top-down parsing. Every S-attributed definition is L-attributed.

Why do compilers use intermediate code?

Intermediate code separates the front end from the back end, so a new target machine needs only a new back end. It is also easier to optimise than source or machine code, because it is simple and machine independent. Common forms are syntax trees, postfix notation and three-address code.

What is three-address code? Write it for a equals b plus c times d.

Each instruction has at most one operator on the right side and at most three addresses. For a equals b plus c times d: t1 equals c times d, then t2 equals b plus t1, then a equals t2. Temporaries like t1 and t2 hold intermediate results.

What are quadruples, triples and indirect triples?

They store three-address code. A quadruple has four fields: operator, two arguments and the result. A triple drops the result field and refers to a result by the triple's position. Indirect triples keep a separate list of pointers to triples, so the optimiser can reorder statements without renumbering references.

What is a DAG and how is it used?

A directed acyclic graph for a basic block has leaves for initial values and interior nodes for operators, with a node shared by every expression that computes the same value. Building it detects common subexpressions, identifies values not used outside the block and shows which statements can be reordered.

Code optimisation

What is code optimisation, and what must it preserve?

Code optimisation transforms intermediate or target code so the program runs faster or uses less memory, while producing exactly the same output for every input. A transformation must be safe and should be worth its cost; machine-independent optimisations work on intermediate code, machine-dependent ones on target code.

What is a basic block, and how do you find leaders?

A basic block is a sequence of statements with one entry at the start and one exit at the end, with no jumps in between. Leaders are the first statement, every target of a jump, and every statement right after a jump. Each block runs from a leader up to the statement before the next leader.

What is a flow graph?

A flow graph has the basic blocks as nodes and an edge from block B1 to B2 when control can pass from the end of B1 to the start of B2, by a jump or by falling through. Loops, dominators and data-flow information such as live variables are found on the flow graph.

Explain constant folding and constant propagation.

Constant folding evaluates expressions with constant operands at compile time, so x equals 2 times 3.14 becomes x equals 6.28. Constant propagation replaces a variable with its known constant value in later uses, which often exposes more folding and dead code.

What is common subexpression elimination?

If an expression such as b times c has already been computed and neither b nor c has changed since, a later occurrence reuses the earlier result instead of recomputing it. In t1 equals b times c and t2 equals b times c plus d, the second uses t1. A DAG finds these within a block.

What is dead code elimination?

Dead code is code whose result is never used, or code that can never execute, such as statements after an unconditional return or inside if false. Removing it saves space and time without changing output. It often appears after constant propagation turns a condition into a constant.

Explain code motion and strength reduction.

Code motion moves a loop-invariant computation, one whose operands do not change inside the loop, to just before the loop, so it is computed once instead of every iteration. Strength reduction replaces an expensive operation by a cheaper one, such as replacing i times 4 for an array index with a variable that adds 4 each iteration.

What is loop unrolling?

Loop unrolling replicates the loop body several times and reduces the number of iterations, for example doing four additions per iteration instead of one. It cuts the loop test and jump overhead and gives the scheduler more instructions to overlap, at the cost of larger code.

What is peephole optimisation?

It examines a small sliding window of target instructions and replaces patterns with shorter or faster ones: removing a redundant load right after a store to the same location, removing unreachable code, collapsing jumps to jumps, simplifying algebra such as adding zero, and using cheaper machine idioms such as an increment instruction.

Code generation and run-time environments

What are the main issues in code generation?

The code generator must select good target instructions for each intermediate operation, allocate and assign registers, and choose an evaluation order, while producing correct code. It depends on the instruction set, the addressing modes and the number of registers of the target machine.

Why is register allocation important, and how is it done?

Registers are far faster than memory but few in number, so keeping heavily used variables in registers speeds up the program. A common method builds an interference graph whose nodes are variables and whose edges join variables live at the same time, then colours it with as many colours as there are registers; uncoloured variables are spilled to memory.

What is an activation record?

An activation record, or stack frame, is the block of memory pushed on the run-time stack for each procedure call. It holds the actual parameters, the return value, the return address, the control link to the caller's frame, the access link for non-local data, saved registers, local variables and temporaries.

Compare static, stack and heap allocation.

Static allocation fixes addresses at compile time, so it cannot support recursion or dynamic sizes. Stack allocation creates an activation record for each call and removes it on return, supporting recursion. Heap allocation gives memory at run time in any order, as with malloc or new, and needs explicit freeing or garbage collection.

What are call by value and call by reference?

In call by value the callee gets a copy of each argument, so changes inside the function do not affect the caller's variables; C uses this. In call by reference the callee gets the address of the argument, so changes are visible to the caller, as with reference parameters in C++. C simulates it by passing pointers.

Parser comparison table

ParserDirectionGrammar it handlesTable sizeViva hook
Recursive descent with backtrackingTop-downNo left recursionNo tableCan be exponential with backtracking
Predictive LL(1)Top-downLL(1): no left recursion, left-factored, unambiguousNon-terminals by terminalsBuilt from FIRST and FOLLOW
Operator precedenceBottom-upOperator grammarsTerminals by terminalsSimple, small class
LR(0)Bottom-upLR(0)Fewest statesReduces regardless of lookahead
SLR(1)Bottom-upSLR(1)Same states as LR(0)Reduces on FOLLOW of the left side
LALR(1)Bottom-upLALR(1)Same states as SLRUsed by YACC and Bison
CLR or canonical LR(1)Bottom-upLR(1), the largest of theseMany more statesMost powerful, largest table

Common mistakes in a compiler design viva

  • Listing the phases out of order, or leaving out the symbol table and error handler that serve all of them.
  • Saying LEX generates a parser. LEX generates a lexical analyser; YACC generates the parser.
  • Forgetting to add dollar to FOLLOW of the start symbol, or adding epsilon to a FOLLOW set. FOLLOW never contains epsilon.
  • Calling a grammar LL(1) without building the table and checking for multiply defined cells.
  • Saying YACC generates an SLR or CLR parser. It generates LALR(1).
  • Mixing up a token and a lexeme.
  • Calling any change an optimisation. It must preserve the program's output for every input.

What the ExamPilot AI examiner checks when you practise

In a CS/IT lab viva session on ExamPilot you name your compiler design experiment, for example a LEX word counter, a YACC calculator or a FIRST and FOLLOW program, and an AI examiner questions you by voice for about twelve minutes: what your program does, which phase it belongs to, a small FIRST and FOLLOW or three-address code exercise said aloud, and a comparison. It follows up whenever an answer is vague. You can answer in English or Hindi.

  • Phase placement: what each phase takes in and what it hands to the next one.
  • LEX and YACC specifics: sections, yytext, yylval, yyparse, and how the two files connect.
  • Worked exercises said step by step: left recursion removal, FIRST and FOLLOW, a three-address sequence.
  • Comparisons with the deciding difference first: SLR versus LALR versus CLR, compiler versus interpreter.
  • Brevity and honesty: two or three sentences, and a clean 'I am not sure' rather than a guess.

Start with the CS/IT lab viva mock. You get a transcript, the questions you fumbled and a tighter answer to say again.

The night before the compiler design lab exam

  1. 1

    Run each LEX and YACC program

    Change one input and predict the output first. Be ready to explain every line in the rules section and the commands you used to build the program.

  2. 2

    Work two grammars by hand

    Remove left recursion from the expression grammar, compute FIRST and FOLLOW, and fill the LL(1) table. Then write three-address code and quadruples for one assignment with three operators.

  3. 3

    Say the phase map aloud

    From characters to tokens to parse tree to annotated tree to three-address code to optimised code to target code, with one example at each step.

  4. 4

    Run one mock viva

    Twelve minutes with the AI examiner on your experiment shows which answers come out clearly and which need work.

Your LEX and YACC actions are written in C, so revise C programming viva questions. Parsing tables and DAGs build on data structures viva questions and DAA viva questions. For how every lab viva works, see the engineering viva hub.

Frequently asked questions

What are the most important compiler design viva questions?
The phases of a compiler and the symbol table, compiler versus interpreter, token versus lexeme, the structure of LEX and YACC programs, ambiguity, left recursion and left factoring, FIRST and FOLLOW, LL(1) tables, handles and shift-reduce parsing, SLR versus LALR versus CLR, three-address code with quadruples and triples, and the main code optimisations. Expect questions on your own program first.
Which parser does YACC generate?
YACC, and its GNU successor Bison, generate LALR(1) parsers in C. The grammar rules and their actions are written in a .y file, and YACC produces y.tab.c containing yyparse. LEX, or Flex, generates the scanner in lex.yy.c with yylex, which the parser calls for tokens.
How do I explain FIRST and FOLLOW quickly in a viva?
Say that FIRST of a string is the set of terminals that can begin something derived from it, and FOLLOW of a non-terminal is the set of terminals that can appear right after it in some sentential form. Then give one example from the expression grammar and mention that both are used to fill the LL(1) table.
Is compiler design asked in placement interviews?
Rarely as a full topic, except for roles in compilers, tooling or systems. Interviewers do ask related basics: compiler versus interpreter, what a linker does, static versus dynamic linking, stack versus heap, and how a program is translated and run. The answers in the basics and run-time sections of this page cover those.
How can I practise compiler design viva questions out loud?
On ExamPilot you can run a CS/IT lab viva by voice. Name your LEX or YACC experiment and the AI examiner asks about it, makes you work a FIRST and FOLLOW or three-address code exercise aloud and follows up like an external examiner, then gives you a transcript with tighter answers. It is free to start.

Practise out loud

Practise your compiler design viva aloud

The AI examiner asks about your LEX or YACC program, makes you place it in a compiler phase and work a parsing exercise aloud, then follows up.

Engineering Viva · CS / IT lab viva

Read how this interview works

Official sources