Compiler Construction
Introduction
Learn how programming-language source code is analysed and transformed into executable representations.
Topic-Wise Overview
Compiler Structure
Compiler versus interpreter and compiler phases
Lexical Analysis
Tokens, regular expressions and finite automata
Syntax Analysis
Grammars, ambiguity, LL and LR parsing techniques
Semantic Analysis
Type checking, symbol environments and intermediate code
Code Generation
Storage organisation, basic blocks, control-flow graphs and optimisation
Study Guidance
Study the complete collection of 200 Compiler Construction MCQs below, organized into four sets of 50. Every question has four choices, its correct answer, and a short explanation. The collection covers compiler phases, lexical analysis, regular expressions, top-down and bottom-up parsing, semantic analysis, symbol tables, intermediate representations, data-flow analysis, optimization, register allocation, runtime systems, linking, and code generation.
Explore Other Subjects
Browse Computer Science subjects
Compiler Construction MCQs — Set 1 (Questions 1–50)
Choose an option and reveal the answer with an explanation.
Question 1. What is the primary function of a compiler?
- Translate program representations
- Change screen colors
- Operate printer
- Format hard disk
Show correct answer and explanation
Correct answer: A. Translate program representations
A compiler translates a program from a source representation to another representation while preserving the intended semantics of valid programs. The output may be machine code, bytecode, or an intermediate language.
Question 2. Which analyses are normally part of a compiler front end?
- Only linking
- Lexical syntax and semantic analysis
- Only register allocation
- Only packaging
Show correct answer and explanation
Correct answer: B. Lexical syntax and semantic analysis
Front-end phases typically scan source into tokens, check grammatical structure, and perform semantic analysis such as name resolution and type checking. They build a representation for later compilation.
Question 3. What is a typical responsibility of a compiler back end?
- Only token recognition
- Only grammar definition
- Target optimization and code generation
- Only comments
Show correct answer and explanation
Correct answer: C. Target optimization and code generation
A back end converts an intermediate representation into target-specific code. It commonly performs instruction selection, register allocation, scheduling, and target-specific optimizations.
Question 4. How does an interpreter normally execute a program?
- Manufactures CPUs
- Only links libraries
- Only edits source
- Executes program representations
Show correct answer and explanation
Correct answer: D. Executes program representations
An interpreter directly evaluates source or an intermediate representation rather than first producing a separate ahead-of-time executable. Some interpreters combine interpretation with just-in-time compilation.
Question 5. What distinguishes a cross-compiler from a native compiler?
- Targets another platform
- Always targets only host
- Only translates English
- Only generates documentation
Show correct answer and explanation
Correct answer: A. Targets another platform
A cross-compiler runs on a host platform but produces code for a different target platform. For example, a desktop compiler may emit instructions for an embedded processor.
Question 6. What is produced by a lexical analyzer?
- CPU opcodes
- Token sequence
- Cache lines
- Executable installer
Show correct answer and explanation
Correct answer: B. Token sequence
Lexical analysis groups source characters into tokens such as identifiers, keywords, literals, and operators. The parser then works with this token stream rather than raw characters.
Question 7. What does a token category represent?
- A physical CPU core
- A parse tree only
- Class of lexeme
- An index page
Show correct answer and explanation
Correct answer: C. Class of lexeme
A token category identifies a class of lexemes, such as IDENTIFIER or NUMBER. The lexeme is the particular source text that matched the category.
Question 8. What is a lexeme in source code?
- A token category label only
- A machine register
- A grammar start symbol
- Matched source substring
Show correct answer and explanation
Correct answer: D. Matched source substring
A lexeme is the exact sequence of source characters recognized for one token. In `count + 1`, the substring `count` is an identifier lexeme.
Question 9. What is an identifier in a programming language?
- Name for programmer-defined entity
- Only a reserved word
- Only punctuation
- Only numeric literal
Show correct answer and explanation
Correct answer: A. Name for programmer-defined entity
Identifiers are names assigned to program entities such as variables, functions, or types. Which character sequences are legal depends on the language’s lexical rules.
Question 10. What is a keyword?
- Only user variable
- Language-defined grammatical word
- Only address offset
- Only comment marker
Show correct answer and explanation
Correct answer: B. Language-defined grammatical word
A keyword is a word with a language-defined syntactic role, such as `while` or `return` in many languages. Reserved keywords cannot be used freely as identifiers.
Question 11. How are regular expressions used in lexical analysis?
- Describe every CFG
- Perform optimization
- Describe lexical patterns
- Emit CPU instructions
Show correct answer and explanation
Correct answer: C. Describe lexical patterns
Regular expressions describe patterns for token classes. Lexer generators commonly translate those patterns into finite automata for efficient scanning.
Question 12. What kinds of languages can a deterministic finite automaton recognize?
- Recognize all CFGs
- Solve halting problem
- Execute a procedure
- Recognize regular languages
Show correct answer and explanation
Correct answer: D. Recognize regular languages
A DFA recognizes precisely the regular languages. Its next state is determined by the current state and the next input symbol.
Question 13. Which algorithm can convert an NFA into an equivalent DFA?
- Subset construction
- Loop unrolling
- Register spilling
- Dead-code removal
Show correct answer and explanation
Correct answer: A. Subset construction
Subset construction represents sets of NFA states as DFA states. The resulting deterministic automaton accepts the same regular language as the original NFA.
Question 14. What does the maximal-munch rule select?
- Shortest possible token
- Longest valid token prefix
- Random character count
- One byte always
Show correct answer and explanation
Correct answer: B. Longest valid token prefix
Maximal munch chooses the longest prefix of the remaining input that matches a token rule. This typically avoids splitting a longer valid operator into shorter tokens.
Question 15. Why do lexical analyzers use rule priorities?
- Changes disk size
- Allocates registers
- Resolves equal-length matches
- Predicts loops
Show correct answer and explanation
Correct answer: C. Resolves equal-length matches
When two token rules match the same longest lexeme, an explicit priority rule determines which category wins. This is useful for keyword-versus-identifier ties.
Question 16. How does a lexer usually handle whitespace?
- Always reject it
- Always parse as a number
- Always encode as opcode
- Skip or tokenize by language rules
Show correct answer and explanation
Correct answer: D. Skip or tokenize by language rules
Whitespace may be ignored, emitted as tokens, or used to delimit structure depending on the language. Indentation-sensitive languages require special treatment.
Question 17. When does a lexical error occur?
- Unmatched character sequence
- Wrong type assignment
- Runtime divide by zero
- Unreachable code
Show correct answer and explanation
Correct answer: A. Unmatched character sequence
A lexical error occurs when the scanner cannot match the next input characters to any valid token rule. A lexer may report the location and attempt recovery.
Question 18. What is the purpose of an end-of-file token?
- Begins a subroutine
- Marks logical input end
- Marks every semicolon
- Contains an integer
Show correct answer and explanation
Correct answer: B. Marks logical input end
An EOF token marks the end of the token stream. Parsers may use it to confirm that a complete grammar start symbol has been recognized without extra input.
Question 19. What does a source-location span record?
- Stores runtime address
- Names CPU register
- Records source text position
- Changes opcode
Show correct answer and explanation
Correct answer: C. Records source text position
Source spans record positions such as line, column, or character offsets for a lexeme or syntax node. Diagnostics use them to point users to the source of an error.
Question 20. What does the Flex tool generate?
- Only generates assembly backends
- Only performs linking
- Only allocates registers
- Generates lexical scanners
Show correct answer and explanation
Correct answer: D. Generates lexical scanners
Flex generates a lexical scanner from rules usually written as regular-expression patterns paired with actions. The generated scanner recognizes tokens in input text.
Question 21. What type of input does a parser receive from a lexer?
- Tokens
- Disk sectors
- Raw electrical signals
- Only object files
Show correct answer and explanation
Correct answer: A. Tokens
A parser usually consumes a token sequence produced by the lexer. Token categories and attached values allow it to check syntax and build structured representations.
Question 22. What does a context-free grammar specify?
- CPU pipeline stages
- Productions over terminals and nonterminals
- Disk addresses
- Only register files
Show correct answer and explanation
Correct answer: B. Productions over terminals and nonterminals
A CFG contains terminal and nonterminal symbols, production rules, and a start symbol. It specifies which strings have syntactically valid derivations.
Question 23. What information is represented by a parse tree?
- Shows hardware caches
- Shows network topology
- Shows grammar derivation structure
- Shows only compiled bytes
Show correct answer and explanation
Correct answer: C. Shows grammar derivation structure
A parse tree records how grammar productions derive the input. Its internal nodes correspond to nonterminals, while its leaves yield the terminal sequence.
Question 24. Which grammar symbol appears at the root of a complete parse tree?
- Last token only
- CPU opcode
- Memory location
- Grammar start symbol
Show correct answer and explanation
Correct answer: D. Grammar start symbol
The root of a complete parse tree is the grammar’s start symbol because the entire input is derived from that symbol.
Question 25. What is the yield of a parse tree?
- Terminal leaves in order
- Only nonterminal names
- Only registers
- Only type qualifiers
Show correct answer and explanation
Correct answer: A. Terminal leaves in order
The yield is the sequence of terminal leaves read left to right. It spells the generated input sentence, ignoring epsilon leaves if present.
Question 26. When is a context-free grammar ambiguous?
- No valid strings
- One string admits two parse trees
- Every word has one parse
- No terminal symbols
Show correct answer and explanation
Correct answer: B. One string admits two parse trees
A grammar is ambiguous if at least one terminal string has two distinct parse trees. Different structures can imply different meanings for the same expression.
Question 27. Which nonterminal is expanded in a leftmost derivation?
- Replace last terminal
- Only replace start once
- Replace leftmost nonterminal
- Never replace variables
Show correct answer and explanation
Correct answer: C. Replace leftmost nonterminal
In a leftmost derivation, each step expands the leftmost remaining nonterminal. The choice of productions determines the final sentence.
Question 28. Which nonterminal is expanded in a rightmost derivation?
- Replace first terminal
- Only process numbers
- Never use productions
- Replace rightmost nonterminal
Show correct answer and explanation
Correct answer: D. Replace rightmost nonterminal
In a rightmost derivation, the rightmost remaining nonterminal is expanded at each step. LR parsing reconstructs such a derivation in reverse.
Question 29. How does an abstract syntax tree differ from a full parse tree?
- Omits unnecessary syntax nodes
- Omits all expressions
- Stores only machine code
- Has only leaf tokens
Show correct answer and explanation
Correct answer: A. Omits unnecessary syntax nodes
An AST usually omits punctuation and grammar-specific scaffolding that do not affect program structure. For example, nested expression nodes retain the operator hierarchy.
Question 30. What constitutes a syntax error?
- An optimizer fails
- Token sequence violates grammar
- A CPU overheats
- A valid variable is unused
Show correct answer and explanation
Correct answer: B. Token sequence violates grammar
A syntax error is a token sequence that cannot be derived from the grammar. Examples include unmatched delimiters or an operator appearing where an operand is required.
Question 31. How does top-down parsing build a derivation?
- Only reduces handles
- Works on machine code only
- Expands from start symbol
- Only emits registers
Show correct answer and explanation
Correct answer: C. Expands from start symbol
Top-down parsing begins with the start symbol and expands nonterminals to match the input. It attempts to construct a leftmost derivation.
Question 32. How does bottom-up parsing recognize a sentence?
- Only scans raw characters
- Only manages pointers
- Only links binaries
- Reduces input toward start symbol
Show correct answer and explanation
Correct answer: D. Reduces input toward start symbol
Bottom-up parsing starts from the input tokens and repeatedly reduces recognized handles toward the grammar’s start symbol. This reverses a rightmost derivation.
Question 33. How is recursive-descent parsing implemented?
- Grammar-directed recursive procedures
- Hardware-only decoding
- No grammar
- Only data-flow analysis
Show correct answer and explanation
Correct answer: A. Grammar-directed recursive procedures
Recursive-descent parsers implement nonterminals as mutually recursive procedures. The procedures match terminals and call each other according to grammar rules.
Question 34. How does a predictive parser choose its next production?
- Always requires backtracking
- Uses lookahead to select production
- Never reads input
- Only operates after code generation
Show correct answer and explanation
Correct answer: B. Uses lookahead to select production
A predictive parser uses the current nonterminal and lookahead token to choose a production without arbitrary backtracking when the grammar supports prediction.
Question 35. What does the notation LL(1) mean?
- Right-to-left with two lookaheads
- Only LR reductions
- Left-to-right leftmost with one lookahead
- Only binary syntax
Show correct answer and explanation
Correct answer: C. Left-to-right leftmost with one lookahead
LL(1) means reading input Left to right, producing a Leftmost derivation, with one lookahead token. A suitable grammar permits an unambiguous table choice.
Question 36. What does FIRST of a grammar symbol describe?
- Possible final registers
- Only trailing terminals
- Only operator precedence
- Possible beginning terminals
Show correct answer and explanation
Correct answer: D. Possible beginning terminals
FIRST describes terminals that may begin strings derivable from a symbol or sequence. It can also contain epsilon if the sequence may derive the empty string.
Question 37. What does FOLLOW of a nonterminal describe?
- Possible terminals after a nonterminal
- Only preceding characters
- Only last CPU states
- Only scope names
Show correct answer and explanation
Correct answer: A. Possible terminals after a nonterminal
FOLLOW(A) is the set of terminals that may occur immediately after nonterminal A in some sentential form. It may include the end marker for the start symbol.
Question 38. When is a nonterminal nullable?
- Must derive a number
- Can derive epsilon
- Cannot derive any terminal
- Always generates a keyword
Show correct answer and explanation
Correct answer: B. Can derive epsilon
A nonterminal is nullable when it can derive the empty string epsilon. Nullable symbols influence FIRST and FOLLOW computations.
Question 39. Why can direct left recursion cause problems for naive recursive descent?
- Always breaks LR parsers
- Only affects machine code
- Naive recursive descent may not consume input
- Only changes type information
Show correct answer and explanation
Correct answer: C. Naive recursive descent may not consume input
A production like A → Aα can call the same recursive-descent procedure before consuming input. Without transformation or special handling, this may recurse indefinitely.
Question 40. What is the purpose of left factoring?
- Removes all variables
- Changes machine endianness
- Eliminates syntax checking
- Extracts common prefixes
Show correct answer and explanation
Correct answer: D. Extracts common prefixes
Left factoring extracts a shared prefix from competing productions. The parser can postpone the choice until enough input distinguishes the alternatives.
Question 41. What information indexes a predictive parsing table?
- Nonterminal and lookahead token
- Register and opcode
- Two disk sectors
- Only program counter
Show correct answer and explanation
Correct answer: A. Nonterminal and lookahead token
A table-driven predictive parser indexes its decision using the current nonterminal and lookahead terminal. The selected cell identifies the production to apply.
Question 42. What does an LL(1) parsing-table conflict indicate?
- Disk space exhausted
- Two choices compete in one table cell
- Only a cache miss
- Linker cannot find library
Show correct answer and explanation
Correct answer: B. Two choices compete in one table cell
An LL(1) conflict occurs when a table cell requires more than one production. The grammar therefore cannot be parsed deterministically by that LL(1) table.
Question 43. What typically appears on the initial stack of a table-driven LL parser?
- All machine instructions
- Only object code
- Start symbol and end marker
- Only symbol table
Show correct answer and explanation
Correct answer: C. Start symbol and end marker
An LL parser typically initializes its stack with the grammar start symbol and an end-of-input marker. Matching proceeds by expansion or terminal consumption.
Question 44. What is panic-mode parser error recovery?
- Guarantee perfect repair
- Remove all lexer rules
- Never report errors
- Discard or synchronize tokens
Show correct answer and explanation
Correct answer: D. Discard or synchronize tokens
Panic-mode recovery discards input tokens or pops grammar symbols until a synchronization point is reached. It helps produce subsequent diagnostics after an error.
Question 45. How do the lexer and parser differ in responsibility?
- Lexer groups characters; parser checks token syntax
- Both only allocate registers
- Parser always precedes lexing
- Both only emit code
Show correct answer and explanation
Correct answer: A. Lexer groups characters; parser checks token syntax
The lexer recognizes words or token patterns from characters; the parser checks how those tokens combine according to grammar productions.
Question 46. What is an example of a token attribute?
- Always a CPU frequency
- Additional value such as numeric literal value
- Only a stack size
- Only an operating-system process
Show correct answer and explanation
Correct answer: B. Additional value such as numeric literal value
Token attributes hold information beyond a category, such as the numeric value of an integer literal or an entry for an identifier in a symbol table.
Question 47. What does a lexer automaton state represent?
- Only a compiled function call
- Only a memory frame
- Represents progress in token pattern recognition
- Only a type checker
Show correct answer and explanation
Correct answer: C. Represents progress in token pattern recognition
A lexer state indicates how far scanning has progressed through possible token patterns. Accepting states identify successful token matches.
Question 48. What is parser lookahead used for?
- Only a future machine instruction
- Only disk contents
- Only previous compiled binary
- Upcoming token used to choose action
Show correct answer and explanation
Correct answer: D. Upcoming token used to choose action
Lookahead examines upcoming tokens before committing to an action. It helps select productions in predictive parsing or shift/reduce decisions in LR parsing.
Question 49. What is a terminal symbol in a grammar?
- An atomic token in grammar productions
- Always a variable to expand
- Only a machine register
- Only a data-flow block
Show correct answer and explanation
Correct answer: A. An atomic token in grammar productions
A terminal symbol is an atomic symbol of the grammar that corresponds to a token consumed from the input. It is not expanded by productions.
Question 50. What is a nonterminal symbol in a grammar?
- Only punctuation
- A syntactic category expanded by productions
- Only a CPU opcode
- Only an assembly label
Show correct answer and explanation
Correct answer: B. A syntactic category expanded by productions
A nonterminal represents a syntactic category such as Expression or Statement. Its production rules specify how it may expand.
Compiler Construction MCQs — Set 2 (Questions 51–100)
Choose a response and reveal the correct answer and explanation.
Question 51. What actions does a shift-reduce parser perform?
- Only scans characters
- Only allocates registers
- Shifts tokens and reduces handles
- Only links binaries
Show correct answer and explanation
Correct answer: C. Shifts tokens and reduces handles
A shift-reduce parser repeatedly shifts input tokens onto a stack and reduces recognized handles using grammar productions. These operations construct a bottom-up parse.
Question 52. What does LR parsing mean?
- Only leftmost derivation
- Needs no stack
- Cannot parse expressions
- Scans left to right and constructs rightmost derivation in reverse
Show correct answer and explanation
Correct answer: D. Scans left to right and constructs rightmost derivation in reverse
LR parsing reads tokens from left to right and reconstructs a rightmost derivation in reverse. LR tables can handle many grammars that are difficult for LL parsers.
Question 53. What is an LR(0) item?
- Production with a dot indicating parse progress
- Only a token name
- Only an AST address
- Only a type
Show correct answer and explanation
Correct answer: A. Production with a dot indicating parse progress
An LR(0) item is a production with a dot marking how much of its right-hand side has been recognized. For example, A → a·b indicates that a has been seen.
Question 54. What is the closure of an LR item set?
- Removes every completed item
- Adds items for nonterminals following dots
- Only emits bytecode
- Only changes terminals
Show correct answer and explanation
Correct answer: B. Adds items for nonterminals following dots
Closure adds items for productions of nonterminals immediately after dots, repeating until no further items can be added. It captures possible parser continuations.
Question 55. What does the GOTO function compute in an LR automaton?
- Performs machine jumps
- Only stores identifiers
- Moves item sets on a grammar symbol
- Only checks types
Show correct answer and explanation
Correct answer: C. Moves item sets on a grammar symbol
GOTO(I, X) advances dots over grammar symbol X in the relevant items of state I and then computes closure. The result is a successor parser state.
Question 56. What is stored in an LR ACTION table?
- Only stores source comments
- Only assigns registers
- Only links object files
- Chooses shift reduce accept or error
Show correct answer and explanation
Correct answer: D. Chooses shift reduce accept or error
An LR ACTION table uses the current state and lookahead terminal to choose shift, reduce, accept, or error. Its conflicts reveal unresolved parsing choices.
Question 57. What is the purpose of the LR GOTO table?
- Chooses next state after reducing a nonterminal
- Only moves scanner bytes
- Only checks semantic types
- Only changes AST leaves
Show correct answer and explanation
Correct answer: A. Chooses next state after reducing a nonterminal
After reducing a right-hand side to nonterminal A, the parser consults GOTO using the exposed stack state and A to choose the next state.
Question 58. When does a shift-reduce conflict arise?
- Only multiple lexemes match
- State and lookahead permit both shift and reduction
- Only no production exists
- Only a missing file
Show correct answer and explanation
Correct answer: B. State and lookahead permit both shift and reduction
A shift-reduce conflict occurs when one state and lookahead allow both shifting and reducing. Precedence rules or grammar changes may resolve it.
Question 59. When does a reduce-reduce conflict arise?
- Two shifts compete
- A token lacks a lexeme
- Two reductions compete at a parsing point
- A stack is empty necessarily
Show correct answer and explanation
Correct answer: C. Two reductions compete at a parsing point
A reduce-reduce conflict occurs when multiple grammar productions could be reduced in the same state with the same lookahead. It creates an ambiguous parser decision.
Question 60. How does SLR parsing determine reduction lookaheads?
- Uses LR(1) lookahead in every item
- Only top-down recursive calls
- No parsing table
- Uses LR(0) items and FOLLOW sets for reductions
Show correct answer and explanation
Correct answer: D. Uses LR(0) items and FOLLOW sets for reductions
SLR uses LR(0) item states and a completed item’s left-hand-side FOLLOW set to authorize reductions. The approximation may introduce conflicts.
Question 61. What additional information does an LR(1) item contain?
- Contains a production position and one-token lookahead
- Only opcode and register
- Only token text
- Only a parse-tree node
Show correct answer and explanation
Correct answer: A. Contains a production position and one-token lookahead
An LR(1) item includes a lookahead terminal in addition to the production and dot position. This more precise context can avoid some SLR conflicts.
Question 62. How are LALR parser states usually formed?
- Always doubles LR(1) states
- Merges LR(1) states with identical LR(0) cores
- Only handles regular languages
- Uses no lookahead
Show correct answer and explanation
Correct answer: B. Merges LR(1) states with identical LR(0) cores
LALR typically merges canonical LR(1) states sharing the same LR(0) core, combining their lookahead sets. This reduces table size but can introduce conflicts.
Question 63. What can an operator-precedence declaration help resolve?
- Always fixes every ambiguous grammar
- Removes all tokens
- Can resolve certain expression grammar conflicts
- Only affects linker
Show correct answer and explanation
Correct answer: C. Can resolve certain expression grammar conflicts
Precedence declarations guide choices such as shift versus reduce for expression operators. They may remove conflicts without rewriting the grammar.
Question 64. How is subtraction conventionally associated in many programming languages?
- Always right associative
- Always nonassociative in every language
- Not part of a grammar
- Conventionally left associative in many languages
Show correct answer and explanation
Correct answer: D. Conventionally left associative in many languages
In many languages subtraction is left associative, so a − b − c is parsed as (a − b) − c. Language specifications determine the actual rule.
Question 65. What causes the dangling-else ambiguity?
- Else may associate with more than one unmatched if
- Only a lexical whitespace error
- Only a type mismatch
- Only an undefined variable
Show correct answer and explanation
Correct answer: A. Else may associate with more than one unmatched if
Nested if statements without explicit delimiters may allow an else to match different preceding if statements. Many languages pair else with the nearest unmatched if.
Question 66. What is a handle in bottom-up parsing?
- Always first character
- Substring matching RHS of the next reverse-derivation reduction
- Only root AST
- Always an identifier
Show correct answer and explanation
Correct answer: B. Substring matching RHS of the next reverse-derivation reduction
A handle is the substring that corresponds to the next production right-hand side in the reverse of a rightmost derivation. Reducing it moves parsing toward the start symbol.
Question 67. What is a viable prefix?
- Any arbitrary invalid string
- Only an EOF token
- Prefix that can appear on an LR parser stack in a valid parse
- A fully optimized expression
Show correct answer and explanation
Correct answer: C. Prefix that can appear on an LR parser stack in a valid parse
A viable prefix is a prefix of a right-sentential form that does not extend beyond a handle’s end. The LR automaton recognizes such stack prefixes.
Question 68. What does the Bison parser generator produce?
- Only allocates physical registers
- Only compresses bytecode
- Only validates disk blocks
- Generates parser code from grammar specifications
Show correct answer and explanation
Correct answer: D. Generates parser code from grammar specifications
Bison generates parser source code from grammar and action specifications. It commonly uses LR-family parsing strategies and produces diagnostic information.
Question 69. How can an error production help parsing?
- A grammar rule supporting recovery or diagnostics
- A mandatory CPU trap
- Only an unreachable block
- Only a lexical pattern
Show correct answer and explanation
Correct answer: A. A grammar rule supporting recovery or diagnostics
An error production explicitly describes malformed input patterns so the parser can recover or report a targeted diagnostic. It must be designed carefully to avoid masking errors.
Question 70. What is the purpose of an AST visitor?
- Only reads machine cache
- Traverses tree nodes to perform operations
- Only links libraries
- Only initializes lexer DFA
Show correct answer and explanation
Correct answer: B. Traverses tree nodes to perform operations
An AST visitor organizes operations that walk tree nodes, such as type checking or code generation. It separates traversal behavior from node definitions.
Question 71. What does semantic analysis check?
- Only groups characters
- Only encodes opcodes
- Checks program meaning such as types and scope
- Only creates backups
Show correct answer and explanation
Correct answer: C. Checks program meaning such as types and scope
Semantic analysis checks constraints not captured by grammar alone, including name binding, types, declarations, and some use-context rules.
Question 72. What information is stored in a symbol table?
- Stores only input characters
- Is always a CPU hash index
- Only records syntax errors
- Maps names to attributes such as type and scope
Show correct answer and explanation
Correct answer: D. Maps names to attributes such as type and scope
A symbol table associates names with properties such as their declared type, source location, storage class, and scope. It helps resolve identifier references.
Question 73. What does the scope of a declaration determine?
- Region in which a declaration or binding is visible
- Only a cache block
- Only file extension
- Only optimization cost
Show correct answer and explanation
Correct answer: A. Region in which a declaration or binding is visible
Scope defines the part of a program in which a binding is visible or eligible for reference. Blocks, functions, and modules may introduce scopes.
Question 74. How does lexical scoping resolve names?
- Only from current call chain
- Resolves names from syntactically enclosing scopes
- Only by CPU register index
- Only from file names
Show correct answer and explanation
Correct answer: B. Resolves names from syntactically enclosing scopes
Lexical scoping resolves a name using scopes determined by the written nesting of the program. It does not depend on which function happened to call another.
Question 75. How does dynamic scoping resolve bindings?
- Only from lexical nesting
- Only from fixed type hierarchy
- Resolves bindings according to active runtime call environments
- Only from code labels
Show correct answer and explanation
Correct answer: C. Resolves bindings according to active runtime call environments
Dynamic scoping looks for an active binding through the runtime call chain. The binding can therefore depend on the sequence of function calls.
Question 76. What is name shadowing?
- Deleting every outer scope
- An invalid syntax in every language
- Only dead-code removal
- Inner declaration hides an outer binding with the same name
Show correct answer and explanation
Correct answer: D. Inner declaration hides an outer binding with the same name
Shadowing occurs when an inner declaration has the same name as one in an enclosing scope. References in the inner scope generally resolve to the nearer declaration.
Question 77. What is name resolution?
- Determines declaration associated with a use
- Only counts tokens
- Only maps source to assembly
- Only writes logs
Show correct answer and explanation
Correct answer: A. Determines declaration associated with a use
Name resolution identifies which declaration a use of a name refers to. It may need to account for imports, overloads, visibility and nested scopes.
Question 78. When is static type checking performed?
- Always discovers all runtime errors
- Checks type constraints without ordinary program execution
- Only occurs after linking
- Means dynamic scope
Show correct answer and explanation
Correct answer: B. Checks type constraints without ordinary program execution
Static type checking validates type constraints before ordinary execution, often during compilation. It can detect invalid operations without running the program.
Question 79. When is dynamic type checking performed?
- Requires all types known at compile time
- Only counts lexical tokens
- Checks type requirements during execution
- Only generates registers
Show correct answer and explanation
Correct answer: C. Checks type requirements during execution
Dynamic type checking validates type requirements during execution using runtime values and metadata. A type error may occur only on a particular execution path.
Question 80. What is type inference?
- Always ignores declarations
- Only changes runtime data
- Only allocates stack frames
- Derives types from expressions and constraints
Show correct answer and explanation
Correct answer: D. Derives types from expressions and constraints
Type inference derives types from expressions and constraints when annotations are incomplete or omitted. The rules depend on the language’s type system.
Question 81. What does type compatibility determine?
- Determines whether types can be used together under language rules
- Only checks identifiers’ lengths
- Only compares machine opcodes
- Only checks comments
Show correct answer and explanation
Correct answer: A. Determines whether types can be used together under language rules
Type compatibility determines whether values or expressions of certain types can be used together, such as assignment to a variable or passing an argument.
Question 82. What is type coercion?
- Only lexical tokenization
- Implicit or explicit conversion between types
- Always an optimizer error
- Only program relocation
Show correct answer and explanation
Correct answer: B. Implicit or explicit conversion between types
Coercion converts a value between types, sometimes implicitly. For example, numeric rules may convert an integer to a floating-point representation.
Question 83. What is an lvalue in relevant language models?
- Always a literal number
- Only a function return type
- Expression denoting a storage location in relevant language models
- Only a branch label
Show correct answer and explanation
Correct answer: C. Expression denoting a storage location in relevant language models
An lvalue generally identifies a location or object that can be referred to, and sometimes assigned to, depending on the language. It differs from a temporary computed value.
Question 84. What is an rvalue?
- Always a storage address only
- Always a grammar variable
- Only a token class
- Expression value used in computation
Show correct answer and explanation
Correct answer: D. Expression value used in computation
An rvalue commonly denotes a value used in an expression rather than an assignable storage location. Exact value-category rules vary by language.
Question 85. What is constant folding?
- Evaluates constant expressions during compilation
- Only identifies keywords
- Always changes algorithm semantics
- Only handles source comments
Show correct answer and explanation
Correct answer: A. Evaluates constant expressions during compilation
Constant folding evaluates compile-time-known expressions, for example replacing 3 × 4 with 12. This saves runtime work when the transformation respects language semantics.
Question 86. What does a declaration-before-use rule require?
- Always means lexical scoping
- Requires name declaration prior to permitted uses in languages enforcing it
- Only a machine constraint
- Only an optimization
Show correct answer and explanation
Correct answer: B. Requires name declaration prior to permitted uses in languages enforcing it
Some languages require declarations before uses so the compiler can resolve the name and its type. Other languages permit forward references under defined rules.
Question 87. What is the key property of static single assignment form?
- Each program has one assignment total
- Only one CPU register exists
- Each SSA variable name is assigned exactly once
- Every block has one instruction
Show correct answer and explanation
Correct answer: C. Each SSA variable name is assigned exactly once
In SSA, each named variable version is assigned exactly once. Creating new versions simplifies analyses of definitions and data flow.
Question 88. Why does SSA use phi functions?
- Only performs numeric multiplication
- Only creates AST tokens
- Only removes comments
- Selects SSA value based on incoming control-flow edge
Show correct answer and explanation
Correct answer: D. Selects SSA value based on incoming control-flow edge
Phi functions choose among versions of a variable according to the incoming control-flow edge at a merge point. This reconciles alternative definitions in SSA.
Question 89. What is an attribute grammar?
- Associates semantic information and rules with grammar symbols
- Only a regular expression
- Only a machine assembler
- Only a disk index
Show correct answer and explanation
Correct answer: A. Associates semantic information and rules with grammar symbols
Attribute grammars attach semantic attributes and evaluation rules to grammar symbols. They formalize syntax-directed calculations such as type or value propagation.
Question 90. How is a synthesized attribute computed?
- Always inherited solely from parent
- Computed from child attributes and local information
- Only a source offset
- Only a CPU interrupt
Show correct answer and explanation
Correct answer: B. Computed from child attributes and local information
Synthesized attributes are calculated using child attributes and local information at a parse-tree node. Information generally flows upward.
Question 91. Where can an inherited attribute obtain its information?
- Always terminal text only
- Only a machine address
- Computed from parent or sibling context under attribution rules
- Only produced by linker
Show correct answer and explanation
Correct answer: C. Computed from parent or sibling context under attribution rules
Inherited attributes may use information from a parent or siblings, subject to the grammar’s evaluation rules. They pass contextual information downward or sideways.
Question 92. How does syntax-directed translation work?
- Only converts binaries to images
- Only runs garbage collection
- Only creates backups
- Uses grammar productions with associated semantic actions
Show correct answer and explanation
Correct answer: D. Uses grammar productions with associated semantic actions
Syntax-directed translation attaches semantic actions to productions. As parsing recognizes constructs, these actions build IR or compute semantic attributes.
Question 93. What is an intermediate representation?
- Compiler-internal form between source and target code
- Only original source characters
- Only physical CPU schematic
- Only final operating system
Show correct answer and explanation
Correct answer: A. Compiler-internal form between source and target code
An intermediate representation is a compiler-internal program form between source analysis and target code. It allows reusable optimizations independent of source syntax.
Question 94. What is three-address code?
- Always uses exactly three memory addresses
- Instruction-like IR with limited operands and destinations
- Only stores source comments
- Only a linker format
Show correct answer and explanation
Correct answer: B. Instruction-like IR with limited operands and destinations
Three-address code decomposes complex expressions into simple operations with explicit temporaries, often with at most two input operands and one result.
Question 95. Which fields usually form a quadruple instruction representation?
- Only four source files
- Only four machine registers
- Often stores operator argument1 argument2 result
- Only four tokens per program
Show correct answer and explanation
Correct answer: C. Often stores operator argument1 argument2 result
A quadruple conventionally stores operator, first argument, second argument, and result. It can encode simple three-address instructions for later passes.
Question 96. What defines a basic block?
- A single source character
- Always a function
- Only a CPU register
- Straight-line instruction region with single entry and exit in a control-flow sense
Show correct answer and explanation
Correct answer: D. Straight-line instruction region with single entry and exit in a control-flow sense
A basic block is a maximal straight-line sequence with one entry at its beginning and control leaving at its end, apart from exceptional control mechanisms.
Question 97. What does a control-flow graph represent?
- Represents basic blocks and possible transfer edges
- Only lexical token sets
- Only register bit widths
- Only source formatting
Show correct answer and explanation
Correct answer: A. Represents basic blocks and possible transfer edges
A CFG has basic blocks as nodes and possible control transfers as edges. It supports reasoning about reachability, loops and program analyses.
Question 98. When does one control-flow node dominate another?
- A is always executed after B
- Node A dominates B if every entry-to-B path passes through A
- A and B have equal identifiers
- Only one predecessor exists
Show correct answer and explanation
Correct answer: B. Node A dominates B if every entry-to-B path passes through A
Node A dominates node B if every path from the CFG entry to B includes A. Dominance is central to SSA construction and optimization.
Question 99. What is data-flow analysis?
- Only recognizes keywords
- Only runs application tests
- Computes facts across program control-flow paths
- Only edits comments
Show correct answer and explanation
Correct answer: C. Computes facts across program control-flow paths
Data-flow analysis propagates facts through a CFG with transfer and merge rules. Examples include liveness and reaching-definitions analysis.
Question 100. What is a type environment?
- Only runtime cache state
- Only an instruction queue
- Only lexer alphabet
- Mapping from in-scope names to type information
Show correct answer and explanation
Correct answer: D. Mapping from in-scope names to type information
A type environment maps currently accessible names to type information. The type checker consults it when validating expressions and statements.
Compiler Construction MCQs — Set 3 (Questions 101–150)
Choose an option and reveal the correct answer and explanation.
Question 101. What is an advantage of using intermediate code in a compiler?
- Separates source analysis from target-specific generation
- Eliminates need for parsing
- Only stores errors
- Requires exactly one target CPU
Show correct answer and explanation
Correct answer: A. Separates source analysis from target-specific generation
An IR separates language-specific source analysis from target-specific code generation. The same middle-end passes can optimize several source languages or hardware targets.
Question 102. What does a three-address assignment representation make explicit?
- Only encodes network packets
- Represents simple computations with explicit temporaries
- Only stores a parse tree
- Requires exactly three pointers
Show correct answer and explanation
Correct answer: B. Represents simple computations with explicit temporaries
Three-address code splits compound expressions into simple operations with temporary variables. Explicit intermediate results are easier for analysis and code generation.
Question 103. What does an edge in a control-flow graph mean?
- Only a variable type
- Only token precedence
- Represents a possible transfer between basic blocks
- Only CPU power flow
Show correct answer and explanation
Correct answer: C. Represents a possible transfer between basic blocks
A CFG edge indicates that execution can transfer from one basic block to another. Conditional branches can create multiple outgoing edges.
Question 104. When does a fall-through control-flow edge occur?
- Only occurs in loops
- Always jumps to program entry
- Only means a function returns
- Transfers control to a subsequent block without an explicit taken branch
Show correct answer and explanation
Correct answer: D. Transfers control to a subsequent block without an explicit taken branch
A fall-through edge connects a block to a following block when execution continues without taking an explicit branch. Its meaning depends on emitted code layout.
Question 105. When is a basic block unreachable?
- Cannot be reached from entry by any CFG path
- Always has no source code
- Always has an infinite loop
- Only contains comments
Show correct answer and explanation
Correct answer: A. Cannot be reached from entry by any CFG path
An unreachable block has no path from the entry in the CFG. Removing it can simplify subsequent optimization when exceptional control flow is properly modeled.
Question 106. What is a loop header in a natural loop?
- Only the final program block
- Block that typically dominates nodes in a natural loop
- Every instruction in the loop
- Only a source keyword
Show correct answer and explanation
Correct answer: B. Block that typically dominates nodes in a natural loop
A natural loop header is the entry point for the loop and dominates its nodes. Back edges into the header characterize common reducible loops.
Question 107. What is a back edge in a control-flow graph?
- Only any edge moving to higher address
- Only an exceptional return
- Control-flow edge to a node dominating its source
- Only a function call
Show correct answer and explanation
Correct answer: C. Control-flow edge to a node dominating its source
An edge from node X to node H is a back edge when H dominates X. Such edges can help identify loops in a reducible CFG.
Question 108. What does a dominator tree represent?
- Only a lexer DFA
- Only data type hierarchy
- Only runtime stack
- Organizes control-flow dominance relationships
Show correct answer and explanation
Correct answer: D. Organizes control-flow dominance relationships
A dominator tree represents immediate-dominator relationships among reachable blocks. Each parent dominates its children, making dominance queries efficient.
Question 109. What is the immediate dominator of a node?
- Closest strict dominator of a node
- Any predecessor chosen at random
- The node itself
- Only its final successor
Show correct answer and explanation
Correct answer: A. Closest strict dominator of a node
The immediate dominator is a node’s closest strict dominator. Every reachable nonentry block has one under the standard single-entry CFG model.
Question 110. What is a postdominator?
- Only a preceding block
- Node on every path from a given node to exit under a defined CFG model
- Only the entry node
- A register assignment
Show correct answer and explanation
Correct answer: B. Node on every path from a given node to exit under a defined CFG model
A postdominator is a block occurring on every relevant path from another block to the exit. Postdominance is often used for control-dependence analysis.
Question 111. What are GEN and KILL sets used for?
- Only token classes
- Only AST node types
- Describe facts created and invalidated by blocks
- Only link symbols
Show correct answer and explanation
Correct answer: C. Describe facts created and invalidated by blocks
GEN identifies facts produced by a block, while KILL identifies facts the block invalidates. They form transfer functions in classical bit-vector analyses.
Question 112. What does reaching-definitions analysis compute?
- Only finds lexical errors
- Only orders functions alphabetically
- Only produces object files
- Determines assignments that may reach each program point
Show correct answer and explanation
Correct answer: D. Determines assignments that may reach each program point
Reaching-definitions analysis finds assignments whose values might reach a program location without an intervening assignment to the same variable.
Question 113. What does live-variable analysis determine?
- Determines values potentially used before being overwritten
- Only counts allocated memory
- Only identifies unused tokens
- Only changes grammar
Show correct answer and explanation
Correct answer: A. Determines values potentially used before being overwritten
A variable is live if its current value may be used later before being overwritten. Liveness information helps determine overlapping register lifetimes.
Question 114. In which direction does backward data-flow analysis propagate facts?
- Always processes only source text backward
- Propagates information from successors toward predecessors
- Only runs after linking
- Only handles regex
Show correct answer and explanation
Correct answer: B. Propagates information from successors toward predecessors
Backward analyses propagate facts from successors to predecessors. Live-variable analysis works backward because later uses determine earlier liveness.
Question 115. In which direction does forward data-flow analysis propagate facts?
- Always reverses machine code
- Only operates on hardware
- Propagates facts from predecessors toward successors
- Only uses parse tables
Show correct answer and explanation
Correct answer: C. Propagates facts from predecessors toward successors
Forward analyses propagate information from predecessors to successors. Reaching-definitions analysis is a standard forward-flow example.
Question 116. What role does a lattice play in data-flow analysis?
- Only a physical circuit
- Only a parser stack
- Only a cache line
- Orders abstract information by precision or inclusion under a framework
Show correct answer and explanation
Correct answer: D. Orders abstract information by precision or inclusion under a framework
A lattice orders abstract program facts and supplies merge operators such as join or meet. Its properties help establish existence and convergence of iterative solutions.
Question 117. What does fixed-point iteration do in static analysis?
- Repeats transfer updates until analysis facts stabilize
- Always executes program
- Only runs linker
- Never terminates for finite frameworks
Show correct answer and explanation
Correct answer: A. Repeats transfer updates until analysis facts stabilize
Fixed-point iteration repeatedly applies transfer and merge operations until no facts change. At that point the analysis has reached a stable solution.
Question 118. What is constant propagation?
- Only merges tokens
- Replaces uses with values proven constant
- Always removes all branches
- Only allocates memory
Show correct answer and explanation
Correct answer: B. Replaces uses with values proven constant
Constant propagation discovers variables whose values are provably constant at a point and substitutes those values when safe. It can expose more folding opportunities.
Question 119. What is copy propagation?
- Only copies files
- Only emits machine loops
- Replaces a copied variable use with its source when safe
- Only folds floating point
Show correct answer and explanation
Correct answer: C. Replaces a copied variable use with its source when safe
Copy propagation replaces uses of a copied variable by its source where definitions and aliases permit. For example, after x = y, a safe use of x may use y.
Question 120. When can dead code elimination remove an instruction?
- Deletes all instructions in loops
- Always removes every store
- Only renames variables
- Removes computations without observable effect under compiler assumptions
Show correct answer and explanation
Correct answer: D. Removes computations without observable effect under compiler assumptions
Dead-code elimination removes operations that have no required observable effects and whose results are not used. Side effects and exceptions must still be respected.
Question 121. What is common-subexpression elimination?
- Avoids repeating an equivalent computation when operands remain valid
- Always changes program output
- Only operates on comments
- Only removes loops
Show correct answer and explanation
Correct answer: A. Avoids repeating an equivalent computation when operands remain valid
Common-subexpression elimination reuses a computed value when an equivalent expression has already been evaluated and its operands remain valid.
Question 122. When is an expression available at a program point?
- Only source file names
- Expressions already computed on all incoming paths without invalidation
- Only function arguments
- Only type errors
Show correct answer and explanation
Correct answer: B. Expressions already computed on all incoming paths without invalidation
An expression is available if it has been computed on every incoming path and none of its relevant operands have subsequently been redefined.
Question 123. What does partial-redundancy elimination achieve?
- Only removes all branches
- Only chooses lexer rules
- Moves or inserts computations to eliminate partially redundant evaluations
- Only compresses binaries
Show correct answer and explanation
Correct answer: C. Moves or inserts computations to eliminate partially redundant evaluations
Partial-redundancy elimination can move or introduce computations to make repeated evaluations fully redundant, then remove them. Correctness depends on control flow and side effects.
Question 124. What is loop-invariant code motion?
- Always makes loops parallel
- Only reorders lexemes
- Only increases recursion
- Moves safe unchanged computations outside a loop
Show correct answer and explanation
Correct answer: D. Moves safe unchanged computations outside a loop
Loop-invariant code motion moves expressions whose values stay constant across iterations outside the loop when moving them cannot change observable behavior.
Question 125. What is strength reduction in optimization?
- Substitutes cheaper equivalent operations under valid semantics
- Always converts int to float
- Only reduces code indentation
- Only deletes branches
Show correct answer and explanation
Correct answer: A. Substitutes cheaper equivalent operations under valid semantics
Strength reduction replaces an operation with a potentially cheaper equivalent one under applicable semantics, such as simplifying address arithmetic in a loop.
Question 126. What is an induction variable?
- Only a lexical identifier
- Variable changing predictably across loop iterations
- Only a program counter
- Any constant literal
Show correct answer and explanation
Correct answer: B. Variable changing predictably across loop iterations
An induction variable changes according to a predictable recurrence across loop iterations, often by adding a constant. Such variables enable simpler address calculations.
Question 127. What does loop unrolling do?
- Always decreases code size
- Eliminates all dependencies
- Duplicates iteration bodies to reduce overhead or expose parallelism
- Only performs tokenization
Show correct answer and explanation
Correct answer: C. Duplicates iteration bodies to reduce overhead or expose parallelism
Unrolling duplicates a loop body across several iterations. It may reduce branch overhead or expose parallelism at the expense of code size.
Question 128. When is loop interchange a legal transformation?
- Only reverses source lines
- Always safe for all programs
- Only a linker optimization
- Swaps nested loop order when dependences permit
Show correct answer and explanation
Correct answer: D. Swaps nested loop order when dependences permit
Interchanging nested loops swaps their order only when loop-carried dependences and language semantics permit. It can improve access locality.
Question 129. What does loop fusion do?
- Combines compatible adjacent loops over related iteration spaces
- Always splits one loop into two
- Only removes variables
- Only allocates registers
Show correct answer and explanation
Correct answer: A. Combines compatible adjacent loops over related iteration spaces
Loop fusion combines compatible loops to reuse data and reduce loop overhead. It is legal only when changing the interleaving of iterations preserves dependencies.
Question 130. What does loop fission do?
- Only executes loops in reverse
- Splits a loop into multiple loops when legal
- Only removes arrays
- Only unrolls loops
Show correct answer and explanation
Correct answer: B. Splits a loop into multiple loops when legal
Loop fission divides one loop into multiple loops. This may isolate operations for vectorization or improve cache behavior, but may increase passes over data.
Question 131. What is function inlining?
- Only stores a function pointer
- Always reduces code size
- Replaces a call with the callee body when valid
- Only compiles headers
Show correct answer and explanation
Correct answer: C. Replaces a call with the callee body when valid
Inlining substitutes the body of a called function at its call site. It can eliminate call overhead and enable optimization across former function boundaries.
Question 132. What is devirtualization?
- Only makes code polymorphic
- Always requires a new class
- Only changes tokens
- Replaces an indirect virtual dispatch with a known direct target when provable
Show correct answer and explanation
Correct answer: D. Replaces an indirect virtual dispatch with a known direct target when provable
Devirtualization replaces an indirect virtual call with a direct target when the compiler can prove which method is invoked, sometimes with guards and fallbacks.
Question 133. What is peephole optimization?
- Examines small instruction windows for local improvements
- Only analyzes entire programs
- Only edits documentation
- Only recognizes grammar tokens
Show correct answer and explanation
Correct answer: A. Examines small instruction windows for local improvements
Peephole optimization examines short sequences of instructions and replaces them with simpler, equivalent sequences. It is typically a local transformation.
Question 134. How can tail-call optimization change function calls?
- Always adds another stack frame
- Can replace eligible final call with frame reuse or jump
- Only affects lexer patterns
- Requires no calling convention
Show correct answer and explanation
Correct answer: B. Can replace eligible final call with frame reuse or jump
An eligible tail call can become a jump or reuse the current stack frame because no further caller computation is needed after the callee returns.
Question 135. What does escape analysis determine?
- Only finds parser errors
- Only reads source comments
- Determines whether objects or references outlive or escape their context
- Only handles registers
Show correct answer and explanation
Correct answer: C. Determines whether objects or references outlive or escape their context
Escape analysis checks whether an object or reference can become accessible beyond a local context. Non-escaping objects may allow stack allocation or scalar replacement.
Question 136. What does alias analysis estimate?
- Only finds same-name identifiers
- Only predicts branch direction
- Only checks syntax
- Estimates whether references may identify the same storage
Show correct answer and explanation
Correct answer: D. Estimates whether references may identify the same storage
Alias analysis determines whether two references can access the same memory location. It helps prove when memory operations may safely move or be eliminated.
Question 137. What does a may-alias result mean?
- Two references might point to the same object or location
- They must always be equal
- They are always disjoint
- They have equal type names only
Show correct answer and explanation
Correct answer: A. Two references might point to the same object or location
May-alias means two references might refer to the same location in some execution. The compiler must conservatively account for that possibility.
Question 138. What does a must-alias result mean?
- They can never coincide
- References necessarily designate the same location under analyzed conditions
- Only addresses different files
- Only variables have same syntax
Show correct answer and explanation
Correct answer: B. References necessarily designate the same location under analyzed conditions
Must-alias means references definitely denote the same location under the analysis assumptions. This stronger guarantee may support additional transformations.
Question 139. What does side-effect analysis identify?
- Only checks comments
- Only stores AST pretty-print output
- Identifies observable changes or interactions of operations
- Only counts functions
Show correct answer and explanation
Correct answer: C. Identifies observable changes or interactions of operations
Side-effect analysis identifies observable consequences such as memory writes, I/O, or exceptions. Optimizations must not remove or reorder required effects.
Question 140. What is a common tradeoff of aggressive inlining?
- Always makes code smaller
- Prevents optimization
- Cannot change instruction cache behavior
- May improve speed but increase code size
Show correct answer and explanation
Correct answer: D. May improve speed but increase code size
Inlining can speed hot call sites, but replicating function bodies increases code size. Excessive size may hurt instruction-cache locality and compilation time.
Question 141. What must a correct compiler optimization preserve?
- Must preserve required observable program behavior
- May freely alter outputs
- Only means source formatting unchanged
- Requires same instruction count
Show correct answer and explanation
Correct answer: A. Must preserve required observable program behavior
Optimization must preserve all behavior required by the source language and compilation assumptions. A faster result is invalid if it changes specified observable semantics.
Question 142. How can undefined behavior influence optimization assumptions?
- Always yields a fixed result
- Can permit optimizers to assume prohibited executions do not occur under that language model
- Only means syntax error
- Always causes a runtime exception
Show correct answer and explanation
Correct answer: B. Can permit optimizers to assume prohibited executions do not occur under that language model
If the language leaves some operations undefined, an optimizer may assume valid programs do not perform them. This requires care because programmers may expect unintended behavior.
Question 143. Why must an optimizer respect integer-overflow semantics?
- Can always treat overflow as harmless
- Never affects transforms
- Depends on signedness and language-specific overflow rules
- Only occurs at link time
Show correct answer and explanation
Correct answer: C. Depends on signedness and language-specific overflow rules
Integer overflow rules differ across languages and signed or unsigned types. Algebraic rewrites are unsafe if they change wraparound, trapping, or undefined behavior.
Question 144. Why can floating-point reassociation change a program’s result?
- Always yields bitwise identical answers
- Only changes instruction count
- Is never legal
- May alter rounding and therefore require language or flag permissions
Show correct answer and explanation
Correct answer: D. May alter rounding and therefore require language or flag permissions
Floating-point calculations round after intermediate operations, so (a+b)+c need not equal a+(b+c). Reassociation may change numerical results unless semantics permit it.
Question 145. What is profile-guided optimization?
- Uses measurements from representative runs to guide transformations
- Only uses source comments
- Requires no runtime data
- Only sets lexer tokens
Show correct answer and explanation
Correct answer: A. Uses measurements from representative runs to guide transformations
Profile-guided optimization uses measurements from representative program runs, such as branch frequencies or hot paths. Unrepresentative profiles can limit benefits.
Question 146. What is just-in-time compilation?
- Only converts code before distribution
- Generates executable code during program execution
- Only edits symbols
- Only performs static linking
Show correct answer and explanation
Correct answer: B. Generates executable code during program execution
JIT compilation generates machine code during program execution. It can use runtime information to specialize and optimize frequently executed code.
Question 147. What is ahead-of-time compilation?
- Must always run inside interpreter
- Only links at runtime
- Generates code ahead of program execution
- Only performs garbage collection
Show correct answer and explanation
Correct answer: C. Generates code ahead of program execution
AOT compilation produces executable or object code before the program runs. It reduces reliance on runtime code generation and may improve startup behavior.
Question 148. What does whole-program optimization use?
- Only processes one token
- Only operates on AST leaves
- Always forbids linking
- Uses information across module boundaries where available
Show correct answer and explanation
Correct answer: D. Uses information across module boundaries where available
Whole-program optimization uses information across available modules or translation units. Broader visibility can enable cross-module inlining and analysis.
Question 149. When does link-time optimization occur?
- Runs compiler optimizations across code at linking stage
- Only chooses lexer rules
- Only evaluates grammar ambiguity
- Only formats disassembly
Show correct answer and explanation
Correct answer: A. Runs compiler optimizations across code at linking stage
Link-time optimization runs compiler analyses or transformations while linking modules, often using stored IR or summaries to make cross-module decisions.
Question 150. Why can the ordering of optimization passes matter?
- Never matters
- Can affect opportunities and resulting performance
- Always determined by alphabetical names
- Only affects comments
Show correct answer and explanation
Correct answer: B. Can affect opportunities and resulting performance
Passes can enable or disable opportunities for other passes. For example, inlining may expose constants for propagation, so order can affect code and performance.
Compiler Construction MCQs — Set 4 (Questions 151–200)
Choose an option and reveal the correct answer and explanation.
Question 151. What does the code-generation phase produce?
- Only recognizes characters
- Only generates parse trees
- Maps IR operations into target machine instructions
- Only checks source indentation
Show correct answer and explanation
Correct answer: C. Maps IR operations into target machine instructions
Code generation lowers intermediate operations to instructions for a target architecture. The result may be assembly, machine code, or a lower-level representation for a later assembler.
Question 152. What is instruction selection?
- Only assigns source token numbers
- Only builds grammar rules
- Only links binaries
- Chooses target instructions for intermediate operations
Show correct answer and explanation
Correct answer: D. Chooses target instructions for intermediate operations
Instruction selection chooses machine instructions that implement IR operations while honoring target constraints. Different choices can affect code size and speed.
Question 153. How does tree-pattern instruction selection work?
- Matches expression trees against target instruction patterns
- Only scans raw characters
- Only performs dynamic linking
- Only allocates stack memory
Show correct answer and explanation
Correct answer: A. Matches expression trees against target instruction patterns
Tree-pattern selection matches IR expression trees against supported target instruction patterns. A cost model may help choose a low-cost covering.
Question 154. What is instruction scheduling?
- Only sorts variable names
- Orders machine operations respecting dependencies and resource constraints
- Always removes all branches
- Only formats source
Show correct answer and explanation
Correct answer: B. Orders machine operations respecting dependencies and resource constraints
Instruction scheduling reorders independent operations while respecting data dependencies and machine constraints. It aims to reduce stalls and improve pipeline usage.
Question 155. What is the goal of register allocation?
- Only creates new source variables
- Only checks grammar ambiguity
- Assigns values to a limited set of machine registers
- Only manages files
Show correct answer and explanation
Correct answer: C. Assigns values to a limited set of machine registers
Register allocation maps temporary values or live ranges to the limited set of hardware registers. Values that do not fit may need to be stored in memory.
Question 156. When is register spilling necessary?
- Deletes all variables
- Only converts integers to floats
- Only links libraries
- Moves selected live values to memory when registers are insufficient
Show correct answer and explanation
Correct answer: D. Moves selected live values to memory when registers are insufficient
Spilling moves selected values to stack or other memory locations because too many values are live for available registers. Loading and storing spills adds overhead.
Question 157. What does an interference graph represent?
- Connects values whose live ranges cannot share one register
- Only represents parsing shifts
- Only shows function calls
- Only describes source characters
Show correct answer and explanation
Correct answer: A. Connects values whose live ranges cannot share one register
An interference graph connects values whose live ranges overlap so they cannot occupy the same register. Each assigned register corresponds to a graph color.
Question 158. How does graph-coloring register allocation work?
- Only colors diagrams
- Assigns register colors to noninterfering live ranges
- Always requires unlimited registers
- Only removes constants
Show correct answer and explanation
Correct answer: B. Assigns register colors to noninterfering live ranges
Graph coloring assigns distinct register colors to interfering live ranges. If the graph cannot be colored using available registers, the allocator may introduce spills.
Question 159. What does register coalescing attempt to accomplish?
- Always merges interfering values
- Only compresses object files
- Combines compatible copy-related live ranges to remove moves
- Only builds lexer DFAs
Show correct answer and explanation
Correct answer: C. Combines compatible copy-related live ranges to remove moves
Coalescing combines compatible live ranges connected by copy instructions. Removing such copies is beneficial if the merge does not create unacceptable interference.
Question 160. How does linear-scan register allocation work?
- Only sorts syntax tokens
- Only uses graph coloring always
- Only manages dynamic linking
- Allocates registers by processing intervals in program order
Show correct answer and explanation
Correct answer: D. Allocates registers by processing intervals in program order
Linear scan processes live intervals in an order related to their program positions. It is relatively fast and is often selected by runtime compilers.
Question 161. What does a calling convention specify?
- Defines argument passing returns and saved registers
- Only defines lexer priority
- Only defines error tokens
- Only optimizes loops
Show correct answer and explanation
Correct answer: A. Defines argument passing returns and saved registers
A calling convention defines how arguments and return values are passed and which registers must survive calls. It is part of the platform’s application binary interface.
Question 162. Which registers must a caller preserve across a call if needed?
- Cannot be modified by callees
- Must be preserved by a caller when its value is needed across a call
- Always stores return address
- Only holds stack pointer
Show correct answer and explanation
Correct answer: B. Must be preserved by a caller when its value is needed across a call
Caller-saved registers may be overwritten by the called function. The caller must save their values when those values are still needed after the call.
Question 163. What obligation applies to callee-saved registers?
- Must always be zero
- Always stores arguments only
- Must be restored by the called routine if it modifies the register
- Cannot be a machine register
Show correct answer and explanation
Correct answer: C. Must be restored by the called routine if it modifies the register
A callee-saved register must be restored by the called function if it modifies that register. This lets callers rely on specified register values remaining intact.
Question 164. What is stored in a function stack frame?
- Only stores global declarations
- Is an assembler’s symbol table
- Only records lexer rules
- Holds activation-specific data such as locals and saved state
Show correct answer and explanation
Correct answer: D. Holds activation-specific data such as locals and saved state
A stack frame commonly contains local variables, saved registers, return-related data, and temporary storage for one invocation. Its exact layout depends on the ABI.
Question 165. What is the role of a stack pointer?
- Tracks a current stack position or boundary
- Always equals program counter
- Only points to disk storage
- Only holds token number
Show correct answer and explanation
Correct answer: A. Tracks a current stack position or boundary
The stack pointer tracks the current stack boundary or position. Instructions use it to allocate and access stack storage for calls and temporary data.
Question 166. Why is a frame pointer useful in some implementations?
- Always stores code address
- Provides a stable reference point for a call frame in implementations using it
- Always required by all compilers
- Only points to constant pool
Show correct answer and explanation
Correct answer: B. Provides a stable reference point for a call frame in implementations using it
A frame pointer provides a stable base for addressing activation-record contents when stack-pointer changes would complicate offsets. Some optimizers omit it.
Question 167. What does a function prologue usually do?
- Only returns to caller
- Only generates tokens
- Establishes necessary stack frame and callee state
- Only performs type inference
Show correct answer and explanation
Correct answer: C. Establishes necessary stack frame and callee state
The prologue establishes the function’s required calling state, for example adjusting the stack pointer and saving callee-preserved registers.
Question 168. What does a function epilogue usually do?
- Only parses arguments
- Only selects grammar production
- Only initializes globals
- Restores saved state and prepares to return
Show correct answer and explanation
Correct answer: D. Restores saved state and prepares to return
The epilogue restores saved state, releases the frame as needed, and transfers control back to the caller. Its details follow the ABI.
Question 169. When is a function call considered a tail call?
- A call in a position where caller has no further computation after it
- Any recursive call
- Only a function with no arguments
- Only a call inside loop
Show correct answer and explanation
Correct answer: A. A call in a position where caller has no further computation after it
A tail call appears where the caller has no further computation after the callee returns. Some implementations can reuse the current frame.
Question 170. What does parameter passing by value mean?
- Always passes the caller variable location
- Supplies a value independent of reassignment to the callee’s parameter binding
- Always copies entire process memory
- Only passes registers
Show correct answer and explanation
Correct answer: B. Supplies a value independent of reassignment to the callee’s parameter binding
Pass-by-value supplies the callee with a value for its parameter binding. Assigning a new value to that binding does not itself reassign the caller’s variable.
Question 171. What does pass-by-reference allow?
- Always copies a numeric literal
- Never permits mutation
- Allows a parameter to refer to a caller-supplied location or object according to language rules
- Only uses stack storage
Show correct answer and explanation
Correct answer: C. Allows a parameter to refer to a caller-supplied location or object according to language rules
Pass-by-reference gives the callee access to a caller-associated location or reference according to language rules. Modifications may therefore be visible to the caller.
Question 172. What is an activation record?
- Only a grammar production
- Only a source token
- Only a linker symbol
- Runtime storage for one procedure invocation
Show correct answer and explanation
Correct answer: D. Runtime storage for one procedure invocation
An activation record stores information for one particular procedure invocation. Multiple recursive calls have distinct activation records.
Question 173. What is the function of a static link in nested routines?
- Provides access to a lexically enclosing activation environment
- Only links object modules
- Only connects cache levels
- Only denotes disk position
Show correct answer and explanation
Correct answer: A. Provides access to a lexically enclosing activation environment
Static links connect a nested routine’s activation to an enclosing lexical environment. They make outer-scope variables accessible at runtime.
Question 174. What is a closure in programming languages?
- Only ends a source file
- Combines executable function behavior with captured lexical environment
- Only a parsing action
- Only a machine instruction
Show correct answer and explanation
Correct answer: B. Combines executable function behavior with captured lexical environment
A closure packages executable function behavior with captured bindings from its lexical environment. It can retain access to data after the enclosing call returns.
Question 175. When is heap allocation useful?
- Only stores temporary local return addresses
- Only recognizes tokens
- Manages objects whose lifetimes need not follow function calls in stack order
- Only performs constant folding
Show correct answer and explanation
Correct answer: C. Manages objects whose lifetimes need not follow function calls in stack order
Heap allocation accommodates objects whose lifetimes do not follow the last-in, first-out order of procedure calls. It normally requires explicit or automatic memory management.
Question 176. What type of object lifetime is well suited to stack allocation?
- Always supports arbitrary free order
- Requires garbage collection for every value
- Only stores globals
- Often supports last-in-first-out lifetime of activation data
Show correct answer and explanation
Correct answer: D. Often supports last-in-first-out lifetime of activation data
Stack allocation is effective for activation data whose lifetimes follow nested calls. Storage can be reclaimed efficiently as stack frames return.
Question 177. What is garbage collection?
- Reclaims unreachable allocated objects under a collector’s reachability model
- Always deletes all heap objects
- Only allocates registers
- Only parses code
Show correct answer and explanation
Correct answer: A. Reclaims unreachable allocated objects under a collector’s reachability model
Garbage collection automatically reclaims memory judged unreachable or otherwise collectable according to the runtime’s memory-management model.
Question 178. How does reference counting manage object lifetime?
- Always detects every reference cycle automatically
- Tracks numbers of owning references to objects
- Only counts instructions
- Only manages lexemes
Show correct answer and explanation
Correct answer: B. Tracks numbers of owning references to objects
Reference counting maintains counts of owning references. A zero count often permits reclamation, although cycles can remain without additional handling.
Question 179. How does a tracing garbage collector identify live objects?
- Only reads source code
- Only checks grammar ambiguity
- Finds reachable objects from roots to identify garbage
- Only generates opcodes
Show correct answer and explanation
Correct answer: C. Finds reachable objects from roots to identify garbage
A tracing collector begins from roots such as stacks and globals, follows references to mark reachable objects, and treats unmarked objects as garbage.
Question 180. Why do generational collectors separate objects by age?
- Only sorts data alphabetically
- Only allocates CPU registers
- Only handles code labels
- Separates objects by age or survival characteristics to improve collection efficiency
Show correct answer and explanation
Correct answer: D. Separates objects by age or survival characteristics to improve collection efficiency
Generational collectors exploit the observation that many newly allocated objects become unreachable quickly. Young and old regions can be collected at different frequencies.
Question 181. What is runtime type information?
- Preserves type-related metadata for runtime operations
- Only stores lexer rules
- Only contains memory addresses
- Only optimizes constant expressions
Show correct answer and explanation
Correct answer: A. Preserves type-related metadata for runtime operations
RTTI is metadata available at runtime for operations such as dynamic type checking, reflection, or casts. The exact facilities depend on the language and runtime.
Question 182. How are exception-handling tables used?
- Only list syntax errors at compile time
- Describe handler regions and unwind information under relevant runtime formats
- Only store cache tags
- Only contain arithmetic constants
Show correct answer and explanation
Correct answer: B. Describe handler regions and unwind information under relevant runtime formats
Exception tables describe protected code ranges, handlers and unwinding actions. The runtime can consult this metadata when an exception propagates.
Question 183. What information can an object file contain?
- Only source comments
- Only a running process
- Contains compiled code data and linking metadata
- Only lexer’s input alphabet
Show correct answer and explanation
Correct answer: C. Contains compiled code data and linking metadata
Object files may contain machine instructions, initialized data, symbol definitions, unresolved references, and relocation entries. A linker combines these into an output artifact.
Question 184. What does symbol resolution accomplish?
- Only finds parse-tree leaves
- Only computes FIRST sets
- Only manages CPU clocks
- Associates references with appropriate symbol definitions
Show correct answer and explanation
Correct answer: D. Associates references with appropriate symbol definitions
Symbol resolution matches a reference in one module to an appropriate definition in another or the same module. Visibility and linkage rules govern which definitions qualify.
Question 185. What is relocation in linking or loading?
- Adjusts address-dependent code or data references after placement
- Only removes grammar ambiguity
- Only marks lexical errors
- Only folds constants
Show correct answer and explanation
Correct answer: A. Adjusts address-dependent code or data references after placement
Relocation adjusts encoded references to account for the actual positions of code and data. A linker or loader may apply relocations after layout is chosen.
Question 186. What happens during static linking?
- Always loads every library at each call
- Combines required code into an output artifact at build time
- Only builds a parse table
- Only performs garbage collection
Show correct answer and explanation
Correct answer: B. Combines required code into an output artifact at build time
Static linking incorporates the required object code and libraries into the produced artifact at build time. This can reduce reliance on separate runtime libraries.
Question 187. What is dynamic linking?
- Requires all code in one file
- Only sorts tokens
- Resolves or loads shared library dependencies through runtime or loader mechanisms
- Only removes code branches
Show correct answer and explanation
Correct answer: C. Resolves or loads shared library dependencies through runtime or loader mechanisms
Dynamic linking connects a program to shared library code through loader or runtime mechanisms. Libraries may be updated or shared without embedding every routine in an executable.
Question 188. What is position-independent code?
- Always contains no addresses
- Only runs without memory
- Only targets one fixed absolute location
- Uses addressing techniques that allow execution from different load addresses
Show correct answer and explanation
Correct answer: D. Uses addressing techniques that allow execution from different load addresses
Position-independent code uses addressing techniques that permit execution at different load addresses. It is useful for shared libraries and address-space layout randomization.
Question 189. What does a linker script control?
- Controls placement and organization of output sections for supported toolchains
- Only defines lexical keywords
- Only configures type checking
- Only handles AST visits
Show correct answer and explanation
Correct answer: A. Controls placement and organization of output sections for supported toolchains
A linker script describes output section layout, addresses, and placement rules for a supporting toolchain. Embedded systems often need explicit memory layouts.
Question 190. What does an executable loader do?
- Only generates source grammar
- Maps program segments and prepares initial execution state
- Only minimizes DFA
- Only allocates virtual registers
Show correct answer and explanation
Correct answer: B. Maps program segments and prepares initial execution state
An executable loader maps program segments into memory, performs required relocations or library setup, and establishes the initial execution state.
Question 191. What is machine-instruction encoding?
- Only stores type names
- Only represents syntax trees
- Expresses target machine instructions as binary fields
- Only records comments
Show correct answer and explanation
Correct answer: C. Expresses target machine instructions as binary fields
Instruction encoding translates a chosen machine operation into the architecture’s prescribed bit fields, such as opcode and operand representations.
Question 192. What does a peephole rewrite change?
- Only changes source whitespace
- Only operates on full source grammar
- Only changes stack address names
- Locally replaces a machine instruction pattern with an equivalent improvement
Show correct answer and explanation
Correct answer: D. Locally replaces a machine instruction pattern with an equivalent improvement
A peephole rewrite substitutes a short local instruction sequence with an equivalent and potentially cheaper one. The rewrite must preserve the required flags and effects.
Question 193. What is a machine-specific optimization?
- Uses target latency registers and instruction constraints
- Only applies syntax rules
- Never considers the ISA
- Only parses regex
Show correct answer and explanation
Correct answer: A. Uses target latency registers and instruction constraints
Machine-specific optimization considers the target processor’s registers, instruction latencies, scheduling rules and addressing modes to improve generated code.
Question 194. What is the purpose of compiler-generated debug information?
- Only contains register passwords
- Maps generated code back to source constructs for debugging
- Only contains grammar ambiguity
- Always removes optimizations
Show correct answer and explanation
Correct answer: B. Maps generated code back to source constructs for debugging
Debug metadata relates generated instruction addresses and machine locations to source lines, names and types. This helps tools inspect optimized programs.
Question 195. What is a source map?
- Only lists CPU caches
- Only stores disk pages
- Associates transformed locations with original source locations
- Only defines token categories
Show correct answer and explanation
Correct answer: C. Associates transformed locations with original source locations
Source maps connect locations in generated or transformed code to locations in original source files. They are especially useful for transpiled or minified programs.
Question 196. What is a compiler diagnostic?
- Always runs executable code
- Only creates machine instructions
- Only measures cache hits
- Reports errors warnings or observations with useful source context
Show correct answer and explanation
Correct answer: D. Reports errors warnings or observations with useful source context
Diagnostics report compilation errors, warnings or notes with useful context such as source positions. Precise explanations help programmers identify and repair problems.
Question 197. What is incremental compilation?
- Rebuilds affected program parts after changes instead of always rebuilding all modules
- Always compiles whole project
- Only handles one token
- Only operates at runtime
Show correct answer and explanation
Correct answer: A. Rebuilds affected program parts after changes instead of always rebuilding all modules
Incremental compilation rebuilds only program regions affected by edits and dependent changes. Correct dependency tracking prevents using stale compiled artifacts.
Question 198. What does a build-system dependency graph track?
- Only represents machine branches
- Tracks relationships that determine what must rebuild
- Only stores runtime call stacks
- Only describes heap objects
Show correct answer and explanation
Correct answer: B. Tracks relationships that determine what must rebuild
A dependency graph represents which build outputs depend on which inputs or targets. It determines rebuild order and what changes require recompilation.
Question 199. What is compiler bootstrapping?
- Only restarts a CPU
- Only performs lexical scanning
- Uses a compiler implementation to help build a compiler for the same or related language
- Only reduces memory usage
Show correct answer and explanation
Correct answer: C. Uses a compiler implementation to help build a compiler for the same or related language
Bootstrapping builds a compiler with an existing compiler, often for its own implementation language. A self-hosting compiler can eventually compile newer versions of itself.
Question 200. What is the goal of compiler validation testing?
- Only checks source formatting
- Guarantees perfect compiler correctness after one test
- Only measures disk usage
- Checks that generated code respects intended language semantics on representative cases
Show correct answer and explanation
Correct answer: D. Checks that generated code respects intended language semantics on representative cases
Validation tests check that generated code behaves according to intended semantics on representative cases. Testing can detect miscompilations but does not prove universal correctness.
