GATE / CS ARCHIVE

SUBJECT COLLECTION

Compiler Design

241 questions, newest first

Download PDF with answers Questions-only PDF

Browse topics
Topic weightage, 2017–2026

Average marks per 100-mark paper across the 15 papers of 2017–2026, with how many questions were asked in that time. Compare subjects

  1. Parsing & Syntax Analysis2.322 questions
  2. Semantic Analysis & Type Checking1.211 questions
  3. Code Optimization & Data-Flow Analysis1.18 questions
  4. Intermediate Code0.55 questions
  5. Lexical Analysis0.34 questions
  6. Compiler Phases, Linking & Loading0.35 questions
  7. Code Generation & Register Allocation Not in GATE 2027 syllabus0.22 questions
  8. Runtime Environments & Parameter Passing0.11 question
  9. Other / Mixed Topics00 questions · last asked 2009
Topic frequency by year
Questions by topic and year
Topic199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
Lexical Analysis001020001100000000002000000100001002
Parsing & Syntax Analysis322021232353415232011222333131320432
Semantic Analysis & Type Checking012111121110210100010000010011211221
Runtime Environments & Parameter Passing525530422121200101010111010000100000
Intermediate Code010120000000100000000001312000100110
Code Optimization & Data-Flow Analysis000000000000000201000003100000301112
Code Generation & Register Allocation100100100000010010011020001000000010
Compiler Phases, Linking & Loading171423110010010000100001111101001100
Other / Mixed Topics101110010000000000100000000000000000

Show
1 mark · MSQ
Report issue

Lexical and semantic errors in C

Lexical Analysis

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

Official answer: C

Givens and goal

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

Approach

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

Step-by-step solution

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

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

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

Original paper, page 21 · Answer key

1 mark · MSQ
Report issue

LL(1) grammar properties

Parsing & Syntax Analysis

Question 28, GATE 2026: Assess four claims: A LL(1) parsers backtrack; B an LL(1) grammar must be left-recursive; C an LL(1) grammar must be left-factored; D LL(1) parsers are more powerful than SLR parsers. The official choice is C, with a retained qualification about literal syntactic left factoring.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: C

Our answer: Official scoring answer C; literal necessity claim is overbroad (see discrepancy).

Givens and goal

Assess four claims: A LL(1) parsers backtrack; B an LL(1) grammar must be left-recursive; C an LL(1) grammar must be left-factored; D LL(1) parsers are more powerful than SLR parsers. The official choice is C, with a retained qualification about literal syntactic left factoring.

Approach

Apply predictive-table conditions rather than treating grammar-transformation advice as an unrestricted necessity theorem.

Step-by-step solution

1. LL(1) selects a production from the next input token using a predictive parsing table. It does not use trial-and-error backtracking, so A is false.
2. Left recursion prevents ordinary predictive top-down parsing; it is something to remove, not a requirement for LL(1). Hence B is false.
3. Left factoring is a standard transformation for removing shared prefixes that obstruct predictive selection. This explains the intended textbook answer C, but syntactic left factoring is not literally necessary for every LL(1) grammar. Left factoring is also not sufficient: FIRST/FIRST or FIRST/FOLLOW conflicts can remain.
4. LL(1) does not have greater grammar-recognition power than SLR parsing. Thus D is false.

Discrepancy / interpretation issue: A reduced, productive counterexample is S → A a | A b, A → ε. The two S alternatives share the syntactic prefix A, so the grammar is not literally left-factored. Nevertheless FIRST(Aa)={a} and FIRST(Ab)={b}; the predictive table selects the two S productions in different columns. For A, its sole epsilon production is selected on FOLLOW(A)={a,b}. There are no conflicts, so the grammar is LL(1). Thus the exact general necessity claim in C is false under the standard syntactic definition of left-factored form. C remains the official scoring answer, but its literal necessity claim requires the qualification above. The issue is not restricted to unreachable or unproductive grammar alternatives.

Review: This counterexample was supplied during independent peer review and checked against FIRST/FOLLOW construction.

Predictive-table check for the counterexample

    Nonterminal   lookahead a      lookahead b
    S             S→Aa             S→Ab
    A             A→ε              A→ε

Each table cell contains at most one production, despite the common written prefix A. For the “more powerful” claim, note also that SLR parsing can handle standard left-recursive grammars such as E→E+a | a, which this predictive LL(1) form cannot parse without transformation. Do not replace the LL(1) table condition with either “left-recursive” or “left-factored” as a complete characterization.

Original paper, page 21 · Answer key

2 marks · MCQ
Report issue

Available expressions at a control-flow merge

Code Optimization & Data-Flow Analysis

Question 42, GATE 2026: The flow is Entry→B1→either B2 or B3→B4→B5→Exit. B1: a=b+i. B2: a=g*k; f=d−f; a=c*4. B3: t=g*k; b=c+m. B4: x=g*k; y=b+i. B5: z=c+m. All variables are integers. Find the redundant expression sets in B4 and B5.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Givens and goal

The flow is Entry→B1→either B2 or B3→B4→B5→Exit. B1: a=b+i. B2: a=g*k; f=d−f; a=c*4. B3: t=g*k; b=c+m. B4: x=g*k; y=b+i. B5: z=c+m. All variables are integers. Find the redundant expression sets in B4 and B5.

Approach

An expression is available only if it has already been computed on every incoming path and neither operand has been reassigned since.

Step-by-step solution

1. The control-flow shape is a diamond followed by a tail:

    B1 ──→ B2 ──┐
      └──→ B3 ──┴──→ B4 ──→ B5

At the B4 merge, availability uses the intersection of the incoming expression sets, not their union.
2. B1 computes b+i. Along B2 neither b nor i is assigned, so this expression remains available there. Along B3, however, b is overwritten by c+m. That kills the old b+i value. Hence b+i is not available on every path to B4 and y=b+i is not globally redundant.
3. Both B2 and B3 compute g*k, and neither subsequently changes g or k. Thus g*k is available along both incoming paths. Its evaluation in x=g*k is redundant. B2 later overwrites a, but that changes the destination holding a previous result, not the operands g and k; a transformation may preserve the value in a temporary.
4. B3 computes c+m, but B2 does not. B4 computes neither c+m nor anything proving its value was previously computed on the B2 path. Therefore z=c+m in B5 is not redundant on all paths.
5. The required sets are B4:{g*k}, B5:empty, option D. Option A wrongly keeps b+i; B wrongly treats a computation on only one branch as universally available; C also incorrectly keeps b+i.

In particular a=c*4 assigns a, not c; the target variable matters when deciding whether an expression is killed.

Original paper, page 31 · Answer key

2 marks · MSQ
Report issue

Two syntax-directed type declarations

Semantic Analysis & Type Checking

Question 53, GATE 2026: G1 has D→TV, T→int|float, V→V₁ id|id; G2 has D→D₁ id|T id, T→int|float. In SDD1, T.type is set by its keyword, D.type=T.type, V.type=T.type, V₁.type=V.type, and each id is entered with V.type. In SDD2, D.type comes from D₁.type or T.type and each id is entered with that child’s type. Decide A same language, B SDD2 S-attributed, C SDD1 L-attributed with only inherited attributes, D same symbol-table entries.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: A, B, D

Givens and goal

G1 has D→TV, T→int|float, V→V₁ id|id; G2 has D→D₁ id|T id, T→int|float. In SDD1, T.type is set by its keyword, D.type=T.type, V.type=T.type, V₁.type=V.type, and each id is entered with V.type. In SDD2, D.type comes from D₁.type or T.type and each id is entered with that child’s type. Decide A same language, B SDD2 S-attributed, C SDD1 L-attributed with only inherited attributes, D same symbol-table entries.

Approach

Compare generated token sequences separately from how attribute values flow through each parse tree.

Step-by-step solution

1. Both grammars generate a type keyword, either int or float, followed by one or more identifier tokens. G1 builds an identifier list through V; G2 builds the same sequence by extending D. Therefore their languages are identical, establishing A.
2. In SDD2, T.type comes from a type keyword and D.type comes from a child T or D. Every attribute value flows upward from children to the left-hand-side symbol, or is a constant. All attributes are synthesized, so SDD2 is S-attributed and B is true.
3. SDD1 passes the type inherited by V down through the identifier list. But it also contains synthesized attributes, including T.type and D.type. Its inherited dependencies are L-attributed, yet the stronger wording that it contains only inherited attributes is false. Thus C is false.
4. In either definition, every identifier receives the same type supplied by the leading keyword. Thus the same identifier/type entries are recorded, establishing D. The ways in which the values flow through the parse tree differ; the resulting entries do not.

Common error: L-attributed does not mean exclusively inherited. An L-attributed definition can contain synthesized attributes as well.

Example: for the token sequence int id₁ id₂, SDD1 obtains int from T and passes it down through V to both identifiers. SDD2 first constructs the declaration for int id₁, synthesizes its type upward, and uses that type when extending the declaration with id₂. Both call put with (id₁,int) and (id₂,int). In SDD1, the existence of the inherited V.type does not erase the synthesized T.type and D.type; that is the exact overstatement in C.

Original paper, page 41 · Answer key

1 mark · NAT
Report issue

Maximal-munch lexical tokens

Lexical Analysis

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

Official answer: 13

Givens and goal

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

Approach

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

Step-by-step solution

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

Original paper, page 23 · Answer key

2 marks · MCQ
Report issue

Counting LR(0) shift-reduce conflicts

Parsing & Syntax Analysis

Question 41, GATE 2026: Use canonical LR(0) parsing for S→ACB, A→aA|ε, C→cC|ε, B→bB|b, with start S. Count shift-reduce conflicts in the ACTION table: A 2; B 3; C 4; D 5.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Step through it (21 steps)

Givens and goal

Use canonical LR(0) parsing for S→ACB, A→aA|ε, C→cC|ε, B→bB|b, with start S. Count shift-reduce conflicts in the ACTION table: A 2; B 3; C 4; D 5.

Approach

Construct the relevant item closures and identify states containing both a shift and a completed item.

Step-by-step solution

1. Augment with S′→S. A completed LR(0) item X→α· requests a reduction on every terminal, without restricting it to FOLLOW(X). It conflicts with any terminal shift present in the same state.
2. The initial state contains S′→·S, S→·ACB, A→·aA, A→·. It shifts a and reduces A→ε, giving one conflicting ACTION cell on a. After shifting a, the state contains A→a·A and the same two A closure items, giving a second conflict on a.
3. After recognizing A, the state contains S→A·CB, C→·cC, C→·. It shifts c and reduces C→ε, giving one conflict on c. After shifting c, the state contains C→c·C with the same C closure items, giving another conflict on c.
4. After recognizing AC, the B closure has B→·bB and B→·b. Shifting b reaches {B→b·B, B→b·, B→·bB, B→·b}. This state shifts b and reduces B→b, giving the fifth conflict.
5. The remaining completed states contain only S′→S·, A→aA·, C→cC·, S→ACB·, or B→bB·; they have no terminal shift. The state before reading B also has no completed item. These account for all 11 canonical states.
6. Therefore there are exactly five conflicting cells, D. Using SLR FOLLOW restrictions instead would be a different parsing method and could change which conflicts remain.

Original paper, page 28 · Answer key

2 marks · MCQ
Report issue

Live variables across a control-flow loop

Code Optimization & Data-Flow Analysis

Question 45, GATE 2026: Blocks execute B1: a=b+c; B2: d=a+e; B3: e=a+f; B4: g=d+e. Edges are entry→B1, B1→B2, B1→B3, B2→B4, B3→B1, B4→exit. No variable is live after exit. Candidate exit sets (B1,B2,B3,B4) are A ({a,b,c,e,f},{d,e},{b,c,e,f},∅); B (∅,{d,e},{a,c,f},∅); C ({a,b,c,e,f},{d,e},{c,e,f},∅); D (∅,{d,e,f},{a,b,c,e,f},∅).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Givens and goal

Blocks execute B1: a=b+c; B2: d=a+e; B3: e=a+f; B4: g=d+e. Edges are entry→B1, B1→B2, B1→B3, B2→B4, B3→B1, B4→exit. No variable is live after exit. Candidate exit sets (B1,B2,B3,B4) are A ({a,b,c,e,f},{d,e},{b,c,e,f},∅); B (∅,{d,e},{a,c,f},∅); C ({a,b,c,e,f},{d,e},{c,e,f},∅); D (∅,{d,e,f},{a,b,c,e,f},∅).

Approach

Solve backward liveness equations to a fixed point, including the loop edge.

Step-by-step solution

1. For each block, OUT is the union of successor IN sets; IN=USE∪(OUT−DEF). Here USE/DEF are B1:{b,c}/{a}, B2:{a,e}/{d}, B3:{a,f}/{e}, and B4:{d,e}/{g}.
2. OUT4=∅, so IN4={d,e}. Hence OUT2={d,e} and IN2={a,e}∪({d,e}−{d})={a,e}.
3. The loop equations are OUT3=IN1, IN3={a,f}∪(IN1−{e}), OUT1=IN2∪IN3, and IN1={b,c}∪(OUT1−{a}). Starting empty and propagating produces the least fixed point IN1={b,c,e,f} and IN3={a,b,c,f}.
4. Substitute back to check: OUT1={a,e}∪{a,b,c,f}={a,b,c,e,f}; removing a and adding b,c indeed gives IN1={b,c,e,f}. OUT3=IN1={b,c,e,f}; removing e and adding a,f indeed gives IN3={a,b,c,f}.
5. The requested exit sets are therefore OUT1={a,b,c,e,f}, OUT2={d,e}, OUT3={b,c,e,f}, OUT4=∅, matching A. In particular b stays live through B3 because the loop can return to B1 and read b before any redefinition.
6. The source assignments and all arrows were inspected visually. Ignoring the back edge would incorrectly remove values needed on a later loop iteration.

Original paper, page 31 · Answer key

1 mark · MCQ
Report issue

Locating symbol-table uses beyond parsing

Semantic Analysis & Type Checking

Question 12, GATE 2025: Which claim about a compiler symbol table is false? A It tracks variable scope. B It can use a binary search tree. C It is no longer needed after parsing. D It is created during lexical analysis.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Approach: Follow identifier information through the compiler rather than treating parsing as the last compilation phase.
A symbol table maps names to attributes such as type, declaration scope and storage location. Scope checking needs those associations, so A describes a normal role. A binary search tree can support lookup and insertion by identifier name, so B is a valid implementation possibility even though hash tables are also common.
After parsing, semantic analysis still needs symbol information for declaration and type checks; later code generation may need storage and addressing attributes. Therefore C’s claim that the table is unnecessary after parsing is false, and C is the keyed answer.
D reflects the conventional introductory pipeline in which lexical analysis begins identifier entries. Real implementations may create or enrich tables at other stages, so D should not be read as a universal requirement on every compiler architecture. The decisive false claim in the intended model is C.

Original paper, page 12 · Answer key

1 mark · MCQ
Report issue

Using liveness for register allocation

Code Generation & Register Allocation

Question 13, GATE 2025: Which compiler activity uses live-variable analysis? A runtime function-call management; B assigning registers to variables; C strength reduction; D constant folding.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Approach: Ask which optimization needs to know whether an existing variable value can be used again.
A variable is live at a program point if some execution path may read its current value before assigning a new value to that variable. Registers hold only a limited number of such values. If two values must remain available at the same time, allocating the same physical register to both can destroy a value that will be needed.
Register allocation therefore uses live ranges, commonly creating an interference edge between values that are simultaneously live. Values whose live ranges do not overlap can reuse a register. This selects B.
Strength reduction, C, replaces an expensive operation with an equivalent cheaper one, while constant folding, D, evaluates expressions with known constants. Neither is identified by the need for liveness in this question. Runtime call management concerns the calling convention and activation records rather than this particular analysis.

Original paper, page 13 · Answer key

2 marks · MSQ
Report issue

Distinguishing FIRST from FOLLOW

Parsing & Syntax Analysis

Question 46, GATE 2025: While computing FIRST and FOLLOW for top-down parsing, select true statements: A A→ε adds ε to FIRST(A); B the input end marker is added to FIRST(S), where S is the start symbol; C A→ε adds ε to FOLLOW(A); D the end marker is added to FOLLOW(S).
Tap to enlarge
Select all that apply
Answer & solution

Official answer: A, D

Approach: Keep separate what a nonterminal can begin with and what can appear immediately after it.
FIRST(A) contains terminals that can start a string derived from A, and includes ε when A can derive the empty string. Therefore the production A→ε makes A true.
FOLLOW(A) contains terminals, or the designated end marker, that may occur immediately after A in a sentential form or completed parse. ε is not an input symbol and never belongs in FOLLOW merely because A is nullable, so C is false. Nullability instead causes FOLLOW information to propagate through nullable suffixes.
The start symbol represents an entire accepted input, so the end marker follows it: D is true. That marker is not automatically the first symbol of any derivation from S, making B false. Thus select A,D. For an ε-production, a predictive parser uses FOLLOW(A) to decide when to take it; it does not put ε into FOLLOW(A).

Original paper, page 46 · Answer key

2 marks · NAT
Report issue

Finding leaders and basic blocks

Code Optimization & Data-Flow Analysis

Question 52, GATE 2025: Partition this three-address code into maximal basic blocks. 1001 i=1; 1002 j=1; 1003 t1=10*i; 1004 t2=t1+j; 1005 t3=8*t2; 1006 t4=t3−88; 1007 a[t4]=0.0; 1008 j=j+1; 1009 if j≤10 goto 1003; 1010 i=i+1; 1011 if i≤10 goto 1002; 1012 i=1; 1013 t5=i−1; 1014 t6=88*t5; 1015 a[t6]=1.0; 1016 i=i+1; 1017 if i≤10 goto 1013. How many blocks?
Tap to enlarge
Answer & solution

Official answer: 6

Approach: Mark every leader: the first instruction, every jump target, and every instruction immediately following a jump when present in the supplied code.
The first instruction makes 1001 a leader. Branch targets make 1003,1002,1013 leaders. The instructions following branches at 1009 and 1011 are 1010 and 1012, so they are leaders too. The branch at 1017 is the last supplied instruction; there is no following instruction to create an extra block.
Sorting the distinct leaders gives 1001,1002,1003,1010,1012,1013. Each block extends to just before the next leader, or to the end: [1001], [1002], [1003–1009], [1010–1011], [1012], [1013–1017]. There are six blocks.
A basic block has one entry and no internal branch out before its end. This explains why even a single assignment at 1002 or 1012 can form its own block: the next instruction is independently a branch target. Counting loops or conditionals alone would not identify the correct partition.

Original paper, page 52 · Answer key

1 mark · MCQ
Report issue

Intermediate Code

Question 21, GATE 2025: For compiler intermediate-code generation, consider: I. backpatching can generate code for Boolean expressions in one pass; II. backpatching can generate code for flow-of-control statements in one pass. Which is correct?
Options: A. I only; B. II only; C. both; D. neither.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

A branch target may not be known when its branch instruction is first generated. Backpatching emits the instruction with a placeholder target and records its location on a list. Later, when the target's instruction address becomes known, the compiler fills that field without rereading the source.

For a Boolean expression such as a<b && c<d, the compiler can keep true and false lists. A true branch from the first comparison is patched to the start of the second comparison; the final true/false branches are patched to the enclosing statement's destinations. This supports short-circuit Boolean code in one pass, so I is true.

For an if, while, or similar statement, next lists and branch lists are patched when the following block, loop test, or exit becomes known. Thus flow-of-control code can also be generated in one pass, making II true. “One pass” does not prohibit editing previously emitted target fields; that editing is precisely the role of backpatching. Answer: C.

Original paper, page 18 · Answer key

1 mark · MCQ
Report issue

Semantic Analysis & Type Checking

Question 22, GATE 2025: Classify these syntax-directed attribute rules:
1. R→AB with B.i=R.i−1, A.i=B.i, R.i=A.i+1.
2. P→CD with P.i=C.i+D.i, D.i=C.i+2.
3. Q→EF with Q.i=E.i+F.i.
Options list the classification of rules 1,2,3 respectively:
A. [S and L], [S not L], [neither].
B. [neither], [S and L], [S and L].
C. [neither], [L not S], [S and L].
D. [S not L], [L not S], [S and L].
Here S means S-attributed and L means L-attributed.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

An S-attributed definition has only synthesized attributes: the parent obtains its values from children. An L-attributed definition additionally permits a child's inherited attributes to depend on the parent's inherited attributes and on attributes of siblings to that child's left, so a left-to-right evaluation is possible.

Rule 1 assigns attributes on both children, so it is not S-attributed. In particular A.i depends on B.i, an attribute of A's right sibling. That violates the L-attributed direction restriction. The listed dependencies also form the cycle R.i→B.i→A.i→R.i; they do not provide a straightforward acyclic evaluation. Thus rule 1 is neither.

In rule 2, P.i is synthesized, but D.i is inherited from its left sibling C. This is permitted in an L-attributed definition and disallowed in an S-attributed one. Rule 3 only synthesizes the parent's Q.i from E.i and F.i, so it is S-attributed, and every S-attributed definition is also L-attributed. The sequence is [neither], [L not S], [S and L], which is C. The letters used to name an attribute, such as i, do not determine its classification; its dependency does.

Original paper, page 19 · Answer key

2 marks · MCQ
Report issue

Parsing & Syntax Analysis

Question 40, GATE 2025: For grammar S→Aa | bAc | dc | bda and A→d, choose the parsing classification.
Options: A. neither LALR(1) nor SLR(1); B. CLR(1) but not LALR(1); C. LALR(1) but not SLR(1); D. both LALR(1) and SLR(1).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Step through it (3 parts)

First compute FOLLOW(A). In S→Aa, a follows A; in S→bAc, c follows A. Thus FOLLOW(A)={a,c}.

The LR(0) state reached by reading d directly from the start contains A→d· and S→d·c. SLR puts the reduction A→d on every symbol in FOLLOW(A), including c, but S→d·c requires shifting c. This is a shift/reduce conflict. Likewise, after reading bd the state contains A→d· and S→bd·a, producing a conflict on a. So the grammar is not SLR(1).

Canonical LR(1) retains the particular context. After the initial d, the completed item is [A→d·,a]; it reduces only on a, while S→d·c shifts c. After bd, the completed item is [A→d·,c]; it reduces only on c, while S→bd·a shifts a. These actions do not conflict.

LALR merges states only when their complete LR(0) cores are identical. The two potentially troublesome states have different S items, S→d·c versus S→bd·a, so they are not merged merely because both contain A→d·. All other reductions arise in completed S productions or similarly nonconflicting states. Hence the precise lookahead separation survives LALR construction. Answer: C.

Original paper, page 30 · Answer key

2 marks · MSQ
Report issue

Parsing & Syntax Analysis

Question 51, GATE 2025: The terminals are if,then,else,a,b,c. Two grammars are:
G1: S→if E then S | if E then S else S | a; E→b.
G2: S→if E then S | M; M→if E then M else S | c; E→b.
Select true statements: A. G1 not LL(1), G2 LL(1); B. G1 LL(1), G2 not LL(1); C. neither LL(1); D. both ambiguous.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: C, D

Write i for the complete terminal phrase “if b then” and e for “else.” In G1, the string i i a e a has two parses: i [i a e a] attaches the else to the inner if, while [i [i a] e a] attaches it to the outer if. This is the dangling-else ambiguity.

G2 may resemble a matched/unmatched-if grammar, but its M production ends in S, not in an entirely matched nonterminal. Consequently an unmatched if can occur in that else branch. A concrete ambiguous string is i i c e i c e c. Its first parse is i [i c e (i c e c)]: the initial S uses S→iS, and its inner S→M derives i c e (i c e c). Its second parse is i [i c e (i c)] e c: the outer S→M uses M→i M e S, with its then-branch M deriving i c e (i c) and its final S deriving c. The else tokens attach to different if occurrences, yet the terminal string is identical. Thus G2 is ambiguous too.

An LL(1) grammar is unambiguous, so neither grammar can be LL(1). Directly, G1's two if-alternatives have the same FIRST token, and G2's S alternatives both admit strings beginning with if. These create predictive parsing conflicts. Select C,D.

Original paper, page 39 · Answer key

1 mark · MSQ
Report issue

Classify parsers by construction direction

Parsing & Syntax Analysis

Question 26, GATE 2024: Which are bottom-up parsers? A Shift-reduce; B Predictive; C LL(1); D LR.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: A, D

Approach: Ask whether parsing starts with the input's terminal symbols and reduces upward, or starts with the grammar's start symbol and expands downward.
1. A shift-reduce parser shifts input symbols onto a stack, then reduces recognized handles to nonterminals. Repeated reductions construct the parse from leaves toward the root. Hence A is bottom-up.
2. An LR parser is a systematic shift-reduce parser. It reads input from left to right and reconstructs a rightmost derivation in reverse, so D is bottom-up as well.
3. Predictive parsing chooses productions while expanding from the start symbol toward the input. It is top-down, making B false.
4. LL(1) is a predictive, top-down method using one lookahead symbol. Its second L refers to a leftmost derivation, not to upward reduction. C is false.
Answer: A and D. LR and LL both scan left to right, so scan direction alone does not distinguish bottom-up from top-down.

Original paper, page 17 · Answer key

2 marks · MCQ
Report issue

Evaluate an SDD including epsilon attributes

Semantic Analysis & Type Checking

Question 37, GATE 2024: An SDD uses S→DHTU with S.val equal to the sum of the four child values. D→M D1 adds 5 to D1.val, while D→ε has value −5. H→L H1 adds 50, while H→ε has value −10. T→C T1 adds 500, while T→ε has value −5. U→K has value 5. For input MMLK, find S.val. A 45; B 50; C 55; D 65.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Step through it (14 steps)

Approach: Split the input according to the grammar and evaluate synthesized attributes from each terminating production upward.
1. D consumes the two Ms: D→M D1→M M D2→M M ε. The bottom value is −5, so D1.val=5−5=0 and D.val=5+0=5.
2. H consumes the single L. Its recursive rule contributes 50, then its epsilon rule contributes −10. Hence H.val=50−10=40.
3. There is no C between L and K, so T immediately uses T→ε. This still assigns T.val=−5; generating no terminal symbols does not mean an attribute value of zero.
4. U consumes K and has U.val=5. The start rule sums the values: S.val=5+40−5+5=45.
Answer: A. The three distinct epsilon base values are part of the semantics and must be applied even when their terminal run is empty.

Original paper, page 23 · Answer key

2 marks · MCQ
Report issue

Recover productions from FIRST and FOLLOW sets

Parsing & Syntax Analysis

Question 38, GATE 2024: A grammar has S→daT | (1), T→aS | bT | (2), R→(3) | ε. FIRST(S)={c,d,f}, FIRST(T)={a,b,ε}, FIRST(R)={c,ε}; FOLLOW(S)=FOLLOW(T)={c,f,$}, FOLLOW(R)={f}. Complete (1),(2),(3). A Rf, ε, cTR; B fR, ε, cTR; C fR, cT, cR; D Rf, cT, cR.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Approach: Use FIRST to eliminate incompatible productions, then verify the surviving option with FOLLOW rather than stopping after a partial match.
1. T must derive ε, and its FIRST set excludes c. Since aS and bT cannot produce ε, the missing alternative is T→ε, not T→cT. This eliminates C and D.
2. FIRST(S) contains c. The existing production daT starts with d. An alternative fR would start only with f, whereas Rf starts with c when R→cTR and with f when R→ε. Thus only A has the required FIRST(S).
3. In A, S→Rf places f immediately after R, giving FOLLOW(R)={f}. R→cTR places a nullable R after T, contributing c and FOLLOW(R)'s f to FOLLOW(T).
4. The trailing T in S→daT inherits FOLLOW(S), while the trailing S in T→aS inherits FOLLOW(T). Because S is the start symbol, $ propagates to both sets. The result is exactly {c,f,$} for each.
Answer: A. FIRST describes how derived strings begin; FOLLOW describes terminals that can occur immediately after a nonterminal in a sentential form.

Original paper, page 24 · Answer key

2 marks · MCQ
Report issue

Partition code into basic blocks

Code Optimization & Data-Flow Analysis

Question 39, GATE 2024: The code is L1 t1=−1; L2 t2=0; L3 t3=0; L4 t4=4*t3; L5 t5=4*t2; L6 t6=t5*M; L7 t7=t4+t6; L8 t8=a[t7]; L9 if t8<=max goto L11; L10 t1=t8; L11 t3=t3+1; L12 if t3<M goto L4; L13 t2=t2+1; L14 if t2<N goto L3; L15 max=t1. Find (number of basic blocks, instructions in largest block). A (6,6); B (6,7); C (7,7); D (7,6).
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Approach: A basic block is a maximal straight-line instruction sequence with entry only at its first instruction and transfer out only at its last. Identify every leader before counting.
1. The first instruction L1 is a leader. Branch targets L11, L4 and L3 are leaders because execution can enter directly at them.
2. Instructions immediately after conditional branches are also leaders: L10 follows L9, L13 follows L12, and L15 follows L14. These are the fall-through paths.
3. Sort the distinct leaders: L1, L3, L4, L10, L11, L13, L15. Each block runs from one leader through the instruction just before the next leader.
4. The blocks are [L1–L2], [L3], [L4–L9], [L10], [L11–L12], [L13–L14], [L15]. Their lengths are 2,1,6,1,2,2,1, totaling all 15 instructions.
Answer: D, seven blocks with largest size six. The terminating branch L9 belongs to its block; a branch target such as L3 begins a new block even when the preceding instruction falls through to it.

Original paper, page 25 · Answer key

1 mark · MCQ
Report issue

Match compiler phases to their products

Compiler Phases, Linking & Loading

Question 21, GATE 2024: Match P lexical analyzer, Q syntax analyzer, R intermediate code generator, S code optimizer to 1 abstract syntax tree, 2 token, 3 parse tree, 4 constant folding. A 4,1,3,2; B 2,3,1,4; C 2,1,3,4; D 4,3,2,1 (listed in P,Q,R,S order).
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Approach: Follow the conventional progression from source characters to structure to intermediate form to optimization.

1. Derivation. Lexical analysis produces tokens(P–2). Syntax analysis constructs a parse tree(Q–3). An abstract syntax tree is a common intermediate representation associated with intermediate-code generation(R–1). Constant folding is a code optimization(S–4). This gives B. Practical compilers can construct ASTs during parsing too; these are the conventional matches among the listed choices, not exclusive ownership of representations.

2. Explanation and checks. A lexer recognizes lexemes such as identifiers and produces tokens; a parser groups tokens according to grammar productions and yields a parse tree. An AST removes grammar-only detail to represent the essential operators and operands, so among these choices it is the intermediate representation. Constant folding replaces an expression such as 3×4 with 12. Real implementations may combine phase boundaries, but B is the intended one-to-one conceptual match.

Original paper, page 15 · Answer key

1 mark · MSQ
Report issue

Recognize the false attribute-evaluation claims

Semantic Analysis & Type Checking

Question 29, GATE 2024: Select FALSE statements. A an attribute grammar is an SDD whose semantic functions have no side effects; B L-attributed definitions cannot always be evaluated depth first; C synthesized attributes can be evaluated during bottom-up parsing; D every L-attributed definition on an LR(1) grammar can be evaluated by bottom-up parsing.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: B, D

Approach: Check the allowed dependency direction and distinguish a completed-tree traversal from evaluation during parsing.

1. Derivation. The question asks for false statements. A is the usual side-effect-free definition of an attribute grammar. L-attributed definitions admit a left-to-right depth-first evaluation, assigning inherited attributes on entry and synthesized ones on return, so B is false. Synthesized attributes can be computed at reductions, making C true. Arbitrary inherited dependencies in an L-attributed definition need not be available at the relevant point in an LR parse, so D’s universal claim about evaluation during bottom-up parsing is false. Thus B, D. Constructing a full parse tree and doing a separate attribute-evaluation traversal is distinct from the intended parsing-time claim.

2. Explanation and checks. An L-attributed production restricts an inherited attribute of a child to information available from the parent and earlier siblings. A left-to-right depth-first traversal can therefore compute it before entering that child and compute synthesized values after returning. A bottom-up reduction naturally has child synthesized values available, but arbitrary inherited context may be required earlier than that reduction. Hence an LR(1) grammar alone does not ensure the claimed parsing-time attribute evaluation. The question asks for the false choices, not the true ones.

Original paper, page 20 · Answer key

2 marks · MCQ
Report issue

Fill four LL(1) parsing-table cells

Parsing & Syntax Analysis

Question 40, GATE 2024: Grammar: S→AaAb | BbBa, A→cS | ε, B→dS | ε. Missing table cells are (1) M[S,c], (2) M[S,d], (3) M[A,b], (4) M[B,a]. Options: A AaAb,BbBa,ε,ε; B BbBa,AaAb,ε,ε; C AaAb,BbBa,blank,blank; D BbBa,AaAb,blank,blank (right sides for the relevant row nonterminal).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Step through it (2 parts)

Approach: Use FIRST for nonempty alternatives and FOLLOW for epsilon alternatives.

1. Derivation. FIRST(AaAb)={c, a}, while FIRST(BbBa)={d, b}. Thus the S-row c cell chooses S→AaAb and the d cell S→BbBa. A occurs before a and b in the first production, so FOLLOW(A)={a, b}; its epsilon production is entered for both lookaheads. Similarly FOLLOW(B)={b, a}, so B→epsilon goes in both a, b cells. Hence cells(1)–(4) are S→AaAb, S→BbBa, A→epsilon, B→epsilon, option A.

2. Explanation and checks. A can disappear, so AaAb can start with a; if A does not disappear it begins with c. The same reasoning yields b or d for BbBa. Each occurrence of A in the S production is followed immediately by a terminal, once a and once b, so both terminals enter FOLLOW(A). The two B occurrences similarly supply b and a. There is no need to put an epsilon production under every lookahead: only FOLLOW lookaheads receive it.

Original paper, page 27 · Answer key

2 marks · MCQ
Report issue

Fill array-load, multiplication and destination triples

Intermediate Code

Question 43, GATE 2024: Expression x[i]=(p+r)*−s[i]+u/w has triples (0) + p r; (1) missing; (2) uminus (1); (3) missing; (4) / u w; (5) + (3) (4); (6) missing; (7) = (6) (5). A fills (1) =[] s i, (3) * (0) (2), (6) []= x i. B uses []= s i, subtraction, =[] x (5). C agrees with A except []= x (5). D uses []= s i, subtraction, =[] x i.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Approach: Follow the expression tree from input values to the final indexed assignment.

1. Derivation. Triple1 must read s[i], denoted =[] s i. Triple2 negates that value. Triple3 multiplies results(0) and(2), forming(p+r)×−s[i]. Triple6 identifies the destination x[i], denoted []= x i, and triple 7 stores the accumulated result(5) there. Only A has all three operations and the correct index i. In C the destination incorrectly uses the computed value(5) as its index.

2. Explanation and checks. A triple refers to the result of an earlier triple by its parenthesized index; (5), for example, denotes the computed right-hand-side value, not the source-language subscript i. Loading s[i] must precede negation. Multiplication then combines p+r with that negative value, followed by addition of u/w. The final destination must still be element i of x. Confusing an array read with a destination reference or substituting the computed value for i changes the program.

Original paper, page 30 · Answer key

2 marks · NAT
Report issue

Compute an LR(0) GOTO closure

Parsing & Syntax Analysis

Question 65, GATE 2024: Augmented grammar: S′→S; S→SS | Aa | bAc | Bc | bBa; A→d#; B→@. Terminals are a,b,c,d,#,@. I0=CLOSURE({S′→·S}). For an SLR parser, how many items are in GOTO(I0,S)?
Tap to enlarge
Answer & solution

Official answer: 9

Step through it (3 steps)

Approach: Move dots over S only where S immediately follows the dot, then close the resulting item set.

1. Derivation. The initial closure contains S′→·S and S→·SS, plus the other four S-start items and A→·d#, B→·@. GOTO on S shifts the first two into S′→S· and S→S·S. The latter requires closure under S, adding all five S-start items: ·SS, ·Aa, ·bAc, ·Bc, ·bBa. Closure of their leading A/B adds A→·d# and B→·@. The total is 2+5+2=9 distinct LR(0) items; SLR FOLLOW sets do not change this item-set construction.

2. Explanation and checks. The full resulting set is S′→S·; S→S·S; S→·SS; S→·Aa; S→·bAc; S→·Bc; S→·bBa; A→·d#; B→·@. The item S→·SS does not generate endlessly many items: closure is a set and revisiting the same production adds no duplicate. Terminals b,d,@ do not cause further closure expansion. Both # and @ are explicitly terminals here, so neither denotes epsilon or the end marker. FOLLOW sets govern SLR reduction entries, not this GOTO construction.

Original paper, page 40 · Answer key

1 mark · MCQ
Report issue

Compiler Phases, Linking & Loading

Question 11, GATE 2023: Assess compiler statements S1: front-end phases are target-hardware independent; S2: back-end phases are target-hardware specific; S3: back-end phases are specific to the source programming language. A S1 only; B S1,S2; C all; D S1,S3.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

The front end analyzes the source language and produces a target-independent representation, making S1 true. The back end maps that representation to the target instruction set and hardware, making S2 true. Source-language-specific analysis is normally a front-end responsibility rather than a back-end phase, so S3 is false. Thus B.

Teaching detail. Lexical analysis, parsing, and semantic/type analysis must understand source-language rules, but need not know the final processor's register set. Conversely, instruction selection, register allocation, and machine-code generation depend on the target. An intermediate representation is the interface separating these responsibilities. Particular compilers may mix optimizations across this boundary, but the question concerns the standard conceptual division; source-language semantics do not become a back-end-specific phase merely because the back end receives their translated representation.

Original paper, page 8 · Answer key

1 mark · MCQ
Report issue

Lexical Analysis

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

Official answer: C

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

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

Original paper, page 16 · Answer key

2 marks · MCQ
Report issue

Code Optimization & Data-Flow Analysis

Question 37, GATE 2023: The control-flow graph has B1: i=m−1;j=n;a=10; B2: i=i+1;j=j−1; B3: a=20; B4: i=a+1. Edges are entry→B1→B2, B2→B3, B2→B4, B3→B4, B4→B2, and B4→exit. Find the live-variable set at each block exit; no values are used after exit.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Liveness means a current value can be read along some future path before redefinition. B4 computes i from a, then can return to B2, where i and j are read; a can also survive to another B4. Thus OUT(B4)={a, i, j}. Before B4 the old i is killed, so IN(B4)={a, j}, yielding OUT(B3)={a, j}. B2 can reach B4 directly or through B3, so OUT(B2)={a, j}; its updates read i, j, yielding IN(B2)={a, i, j}=OUT(B1). Therefore D.

Teaching detail. Use OUT(B)=the union of IN over successor blocks and IN(B)=USE(B) union (OUT(B)−DEF(B)). Here USE(B2)={i,j}, DEF(B2)={i,j}, USE(B3)=∅, DEF(B3)={a}, USE(B4)={a}, DEF(B4)={i}. The loop requires a fixed point rather than a single backward pass. Crucially j remains live through B4 because the next B2 reads it; old i is killed inside B4 but the newly assigned i is live afterward. Values m,n are used only in B1 and are not live at its exit.

Original paper, page 37 · Answer key

2 marks · NAT
Report issue

Semantic Analysis & Type Checking

Question 60, GATE 2023: Syntax-directed rules: N→I#F gives N.val=I.val+F.val; I→I1 B gives I.val=2I1.val+B.val and I→B copies B.val; F→B F1 gives F.val=(B.val+F1.val)/2 and F→B gives B.val/2; B→0 or 1 takes the bit value. Evaluate 10#011 to three decimals.
Tap to enlarge
Answer & solution

Official answer: 2.374 to 2.376

Our answer: 2.375

Step through it (19 steps)

The I rules interpret the left substring as a binary integer: I(10)=2*1+0=2. Evaluate the fractional suffix from right to left: F(1)=1/2, F(11)=(1+1/2)/2=3/4, and F(011)=(0+3/4)/2=3/8. Thus N.val=2+3/8=2.375, within the official interval 2.374 to 2.376.

Teaching detail. The separator # plays the role of a binary radix point in these semantic rules, not a multiplication or concatenation operator on numbers. The left-recursive integer production multiplies the accumulated prefix by two before appending the next bit. The right-recursive fractional production halves the sum of the current bit and the suffix fraction, placing successive bits at weights 1/2,1/4,1/8. Directly, 10#011 represents 2+0/2+1/4+1/8. This corroborates the synthesized-attribute evaluation and yields an exact terminating decimal.

Original paper, page 63 · Answer key

1 mark · MCQ
Report issue

Parsing & Syntax Analysis

Question 13, GATE 2022: Choose the true statement: A LALR(1) cannot introduce reduce/reduce conflicts absent from LR(1); B symbol tables are accessed only during lexical analysis; C data-flow analysis is necessary for run-time memory management; D LR(1) parsing suffices for deterministic context-free languages.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Every deterministic context-free language has an LR(1) grammar, so LR(1) parsing is sufficient for these languages, D. LALR merging can introduce reduce-reduce conflicts even when canonical LR has none. Symbol-table information is used beyond lexical analysis, and data-flow analysis is not a necessary runtime step in program execution. The claim is about existence of a suitable LR(1) grammar, not that every grammar of the language is LR(1).

LALR merges canonical states with identical LR(0) cores but potentially different lookahead sets; combining these lookaheads can create a reduce/reduce choice. Symbol tables also serve declaration/type checking, code generation, and optimization. LR(1) sufficiency concerns a grammar for the language, not every arbitrary presentation of it.

Original paper, page 12 · Answer key

1 mark · NAT
Report issue

Parsing & Syntax Analysis

Question 29, GATE 2022: Grammar: S′→S; S→S+R|R; R→R*P|P; P→(S)|id. Let I0={S′→S·, S→S·+R}. Count items in goto(closure(I0),+).
Tap to enlarge
Answer & solution

Official answer: 5

Step through it (3 steps)

Taking goto on + advances S→S·+R to S→S+·R. Closure then adds R→·R*P, R→·P, P→·(S), and P→·id. No dot precedes S in these items, so no further closure is needed. Total 5 items.

Closure only expands a nonterminal immediately after a dot. Initially the dots precede end-of-rule or terminal +, so closure(I0)=I0. After shifting +, R is exposed; recursively expanding R and P yields the five items listed. The left-recursive R production is added once, so closure terminates.

Original paper, page 22 · Answer key

2 marks · NAT
Report issue

Semantic Analysis & Type Checking

Question 65, GATE 2022: Translation grammar: S→S1#T gives S.val=S1.val*T.val; S→T copies T.val; T→T1%R gives T.val=T1.val/R.val; T→R copies R.val; R→id copies integer id.val. Evaluate root S.val for 20#10%5#8%2%2. The source lists an unused nonterminal P as well.
Tap to enlarge
Answer & solution

Official answer: 80

Step through it (28 steps)

The grammar gives % higher precedence than #, with both operators left-associative. Their semantic operations are division and multiplication, respectively, rather than C remainder. The three T values are 20, 10/5=2, and (8/2)/2=2. The left-associative S combination therefore gives (20*2)*2=80. The printed nonterminal list includes an unused P, but no production or calculation depends on it.

The parse groups as (20 # (10 % 5)) # ((8 % 2) % 2). The left recursion in T fixes the latter association, so its value is (8/2)/2=2 rather than 8/(2/2)=8. S’s translation multiplies the three T values: 20×2×2=80.

Original paper, page 41 · Answer key

1 mark · MCQ
Report issue

Runtime Environments & Parameter Passing

Question 4, GATE 2021: S1: The sequence of procedure calls is a preorder traversal of the activation tree. S2: The sequence of procedure returns is a postorder traversal. Which is correct? A S1 true/S2 false; B S1 false/S2 true; C both true; D both false.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

A procedure activation is entered before its child calls, producing preorder. It returns only after its nested calls finish, producing postorder. Thus both statements are true, C, in the ordinary sequential, properly nested call-return model.

For example, if main calls A, A calls B and C in order, and main then calls D, the entry order is main,A,B,C,D. The completion order is B,C,A,D,main. These are exactly preorder and postorder on the ordered activation tree. Recursive calls create distinct activation nodes even when the procedure name repeats; one must not merge all calls of the same procedure into a single node.

Original paper, page 13 · Answer key

1 mark · MCQ
Report issue

Parsing & Syntax Analysis

Question 5, GATE 2021: S1: Every SLR(1) grammar is unambiguous, but some unambiguous grammars are not SLR(1). S2: For every context-free grammar there is a parser taking at most O(n³) time for an input of length n. Which is correct? A S1 true/S2 false; B S1 false/S2 true; C both true; D both false.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

A conflict-free SLR(1) table yields a unique parse, so every SLR(1) grammar is unambiguous. The converse fails: the standard grammar S→L=R|R, L→*R|id, R→L is unambiguous but has an SLR shift-reduce conflict. General CFG recognition and construction of a parse can be done in O(n³) for a fixed grammar, for example by Earley parsing or CYK after normalization. Thus both statements hold, C; this does not claim that exponentially many parse trees can all be listed in cubic time.

In the counterexample grammar, the LR(0) state after recognizing L contains S→L·=R and R→L·. Since '=' belongs to FOLLOW(R), SLR would both shift '=' and reduce R→L there. Thus unambiguity alone does not remove SLR conflicts. For cubic parsing, CYK stores whether each nonterminal derives each substring and considers O(n) split points for O(n²) substrings; the fixed grammar contributes only a constant factor. A parse witness can be recovered by stored backpointers.

Original paper, page 14 · Answer key

2 marks · MCQ
Report issue

Semantic Analysis & Type Checking

Question 26, GATE 2021: A grammar and SDT are: P→D* E*; D→int ID records the identifier as int; D→bool ID records it as bool; E→E1+E2 checks E1.type=E2.type=int and sets E.type=int; E→!E1 checks E1.type=bool and sets E.type=bool; E→ID unconditionally sets E.type=int. Which claim holds? A correctly type-checks every syntactically correct program; B type-checks syntactically correct integer declarations and integer expressions; C type-checks syntactically correct boolean declarations and boolean expressions; D leads to an infinite loop.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

The ID expression action unconditionally sets its type to int instead of consulting the declarations. Consequently integer-only, properly declared expressions using + receive the intended types, but a declared boolean is still labeled int and a valid negation can be rejected. The finite semantic actions do not themselves loop. Thus B. As usual, the limited claim assumes the mentioned integer identifiers have valid declarations; the displayed action does not implement undeclared-variable checking.

Trace a valid boolean declaration/expression: bool flag; !flag. The declaration records bool, but E→ID labels flag as int; the negation action then demands bool and rejects a valid expression. Conversely int a; int b; a+b labels both operands int and passes. A corrected ID action would look up ID.lexeme in the symbol table, reject undeclared identifiers, and copy the declared type. Thus the exact defect is the unconditional int assignment, not the grammar's use of repetition.

Original paper, page 23 · Answer key

2 marks · MCQ
Report issue

Parsing & Syntax Analysis

Question 31, GATE 2021: For terminals {a,b,c,d,f}, grammar S→daT|Rf, T→aS|baT|ε, R→caTR|ε has a partially filled LL(1) table. Numbered cells are 1=(S,c), 2=(S,f), 3=(T,c), 4=(T,$). Known cells are (S,d)=S→daT; (T,a)=T→aS; (T,b)=T→baT; (T,f)=T→ε; (R,c)=R→caTR; (R,f)=R→ε; other unnumbered cells blank. Choose entries (1,2,3,4): A (S→Rf,S→Rf,T→ε,T→ε); B (blank,S→Rf,T→ε,T→ε); C (S→Rf,blank,blank,T→ε); D (blank,S→Rf,blank,blank).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Step through it (2 parts)

FIRST(R)={c,ε}, so FIRST(Rf)={c, f}; both numbered S-row cells contain S→Rf. From R→caTR, c belongs to FOLLOW(T), and nullable R carries FOLLOW(R)={f} into FOLLOW(T). From S→daT and T→aS, the start marker $ also reaches FOLLOW(T). Thus FOLLOW(T)={c, f,$}, and the numbered T-row cells at c and $ contain T→ε. Therefore A.

The FIRST rule puts A→α in every terminal column of FIRST(α) except ε. When α is nullable, put it in all FOLLOW(A) columns. For S→Rf, R can start with c or disappear, exposing f. For T→ε, the c column comes from T followed by R in R→caTR; the f column comes from the following nullable R and S→Rf; the end marker flows from start S through S→daT. No guessed table entry is needed once these sets are computed.

Original paper, page 27 · Answer key

2 marks · NAT
Report issue

Code Optimization & Data-Flow Analysis

Question 50, GATE 2021: A compiler represents this basic block by a common-subexpression DAG: a=b+c; e=a+1; d=b+c; f=d+1; g=e+f;. How many DAG nodes are needed? The symbol in the additions to a and d is the constant digit 1.
Tap to enlarge
Answer & solution

Official answer: 6

The code uses the constant 1, not a variable i. A common-subexpression DAG has three leaves b, c, 1. One addition node b+c is labeled by both a and d. A second addition node (b+c)+1 is labeled by both e and f. The final addition node adds that second node to itself and is labeled g. Hence there are 3 leaves plus 3 operation nodes, totaling 6. Variable labels are not separate DAG nodes in this representation.

Name the six nodes: n1=b, n2=c, n3=constant 1, n4=+(n1,n2) labeled a,d, n5=+(n4,n3) labeled e,f, n6=+(n5,n5) labeled g. The code does not change b or c, so the two b+c expressions really share one node. Repeated variable names attached as labels are not new values/nodes. This is common-subexpression DAG construction, not a syntax tree that duplicates every appearance or algebraic strength reduction to multiplication.

Original paper, page 39 · Answer key

1 mark · MCQ
Report issue

Semantic Analysis & Type Checking

Question 3, GATE 2021: ANSI C program: int main(){ Integer x; return 0; }. No declaration of Integer is supplied. Which conceptual seven-phase compiler stage reports the error? A lexical analysis; B syntax analysis; C semantic analysis; D machine-dependent optimization.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Our answer: C in the textbook phase model

Integer is an identifier rather than a built-in C type, and no typedef declaration introduces it. The intended seven-phase classification is an undeclared-type/name error detected by semantic analysis, C. Real C front ends can report a parse error because typedef-name classification interacts with parsing; the answer describes the conceptual phase classification rather than a guarantee about every compiler diagnostic.

Lexing can recognize Integer as a legal identifier, so its spelling is not itself a lexical error. Semantic analysis normally resolves declarations and type meanings. The conceptual answer should not be read as promising that a particular real C parser will proceed to a separately named semantic phase for this malformed declaration.

Original paper, page 56 · Answer key

1 mark · MSQ
Report issue

Intermediate Code

Question 13, GATE 2021: Which is NOT an intermediate representation of source computation? A three-address code; B abstract syntax tree; C control-flow graph; D symbol table. Multiple selections are permitted.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: D

Three-address code, an abstract syntax tree, and a control-flow graph represent program computations or structure. A symbol table instead records information about names, types, scopes, and bindings. It supports analysis but is not an intermediate representation of the source computation. Thus D.

For an assignment x=a+b, three-address code records the operation, an AST records its expression structure, and a CFG records possible control transfers around it. The symbol table instead stores facts such as x's declared type or scope. A compiler may use all four structures; “used by a compiler” is broader than “intermediate representation.”

Original paper, page 62 · Answer key

2 marks · MCQ
Report issue

Code Optimization & Data-Flow Analysis

Question 30, GATE 2021: Code: z=x+3+y->f1+y->f2; for(i=0;i<200;i=i+2){if(z>i){p=p+x+3;q=q+y->f1;}else{p=p+y->f2;q=q+x+3;}}. y points to a heap struct; x,y,z,p,q,i reside in registers. After common subexpression elimination, count additions and field dereferences. A (403,102); B (203,2); C (303,102); D (303,2).
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Compute and reuse x+3, y->f1, and y->f2. The initial expression then uses 3 additions and 2 dereferences. There are 100 loop iterations; either branch needs one addition for p and one for q, and the increment i=i+2 needs one more. Thus total additions 3+100·3=303, while both dereferenced fields remain reusable because the loop does not modify them. Answer D, under the specified CSE model.

An optimized schematic is u=x+3;v=y->f1;w=y->f2;z=u+v+w; followed by branches (p+=u;q+=v) or (p+=w;q+=u). There are 100 iterations because i runs 0,2,…,198. CSE does not erase the loop-counter addition or the two updates in either branch. The count assumes the problem's arithmetic regrouping/CSE model and no intervening field writes or aliasing stores.

Original paper, page 71 · Answer key

2 marks · MCQ
Report issue

Code Optimization & Data-Flow Analysis

Question 38, GATE 2021: USE(S) means variables used in S; IN(S),OUT(S) are live variables on entry/exit. Basic block is S1 followed by S2. A OUT(S1)=IN(S2); B OUT(S1)=IN(S1)∪USE(S1); C OUT(S1)=IN(S2)∪OUT(S2); D OUT(S1)=USE(S1)∪IN(S2).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Inside a basic block S1 has S2 as its unique immediate successor. Values live just after S1 are exactly those live just before S2, so OUT(S1)=IN(S2), A. Uses at S1 do not automatically remain live afterward, and a definition in S2 can kill a value that is live after S2.

The general equations are OUT(S)=union of IN of immediate successors, and IN(S)=USE(S)∪(OUT(S)−DEF(S)). A basic block has no branch between S1 and S2, reducing the first equation to A. For example S1 reads x then S2 overwrites x: x can be used at S1 without needing to remain live after it, refuting formulas that force USE(S1) into OUT(S1).

Original paper, page 77 · Answer key

2 marks · NAT
Report issue

Parsing & Syntax Analysis

Question 51, GATE 2021: Augmented grammar S′→S; S→S#cS | SS | S@ | <S> | a | b | c. I0=CLOSURE({S′→·S}). Count LR(0) items in GOTO(GOTO(I0,<),<).
Tap to enlarge
Answer & solution

Official answer: 8

Step through it (4 steps)

On reading < from the initial closure the kernel is S→<·S>. Its closure adds all seven S productions with the dot at the beginning: S→·S#cS, ·SS, ·S@, ·<S>, ·a, ·b, ·c. Reading a second < reproduces exactly the same kernel and closure. Thus GOTO(GOTO(I0,<),<) has 1+7=8 items; the augmented S-prime item is not added because closure expands only S.

The resulting item set is {S→<·S>, S→·S#cS, S→·SS, S→·S@, S→·<S>, S→·a, S→·b, S→·c}. Recursive closure does not create infinitely many copies: items are set members. In particular, productions beginning with S are added once and their expansion adds no new productions beyond the seven already present.

Original paper, page 86 · Answer key

1 mark · MCQ
Report issue

Compiler Phases, Linking & Loading

Question 9, GATE 2020: Test I: symbol tables are accessed only in lexical and syntax analysis. II: supporting recursion necessarily requires heap allocation. III: declaration-before-use errors are detected during syntax analysis. Options: A I only; B I and III; C II only; D none.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Worked explanation

A symbol table records information such as declarations, types and locations. Type checking needs that information in semantic analysis, and code generation may need offsets and storage locations, so “only” makes I false. Recursive calls need distinct activation records, but their last-in-first-out lifetimes are exactly what a runtime stack handles; a heap is not logically necessary. Finally, syntax checks whether token sequences fit grammatical productions, whereas whether a particular name has already been declared depends on the binding environment. That contextual condition belongs to semantic analysis in the conventional compiler-phase distinction used here.

Derivation and answer

Semantic analysis and code generation also consult symbol-table information, refuting I. Ordinary nested recursion can be supported with stack activation records and does not inherently need a heap, refuting II. Declaration-before-use is a contextual semantic condition, not ordinary context-free syntax checking, refuting III. Thus none, D.

Original paper, page 5 · Answer key

1 mark · NAT
Report issue

Parsing & Syntax Analysis

Question 24, GATE 2020: Grammar: S→aSB | d; B→b. How many reductions does a bottom-up parser perform to accept aaadbbb?
Question 24, GATE 2020: Grammar: S→aSB | d; B→b. How many reductions does a bottom-up parser perform to accept aaadbbb?
Tap to enlarge
Answer & solution

Official answer: 7

Step through it (16 steps)

Worked explanation

An explicit reduction sequence is aaadbbb ⇒ aaaSbbb ⇒ aaaSBbb ⇒ aaSbb ⇒ aaSBb ⇒ aSb ⇒ aSB ⇒ S. The first step uses d→S; each pair thereafter uses b→B followed by aSB→S. Thus there are 1+3+3=7 reductions. The corresponding derivation tree has four S-production nodes and three B-production nodes. A bottom-up parser may also shift seven terminals and eventually perform an accept action; neither shifts nor accept are additional grammar reductions.

Derivation and answer

The derivation uses S→aSB three times, S→d once, and B→b three times. A bottom-up parse reverses these seven production applications, so it performs 7 reductions, excluding the separate parser accept action.

Original paper, page 9 · Answer key

2 marks · MCQ
Report issue

Semantic Analysis & Type Checking

Question 33, GATE 2020: Productions A→PQ and A→XY have inherited i and synthesized s attributes on each nonterminal. Rule 1: P.i=A.i+2; Q.i=P.i+A.i; A.s=P.s+Q.s. Rule 2: X.i=A.i+Y.s; Y.i=X.s+A.i. Which are L-attributed? A both; B only Rule 1; C only Rule 2; D neither.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Worked explanation

An inherited attribute of a child in an L-attributed definition may depend on inherited attributes of the parent and attributes of siblings to its left. In A→PQ, P has no left sibling, and its inherited value depends only on A.i. Q can use P.i because P is left of Q. Synthesized A.s is evaluated after both children return. A valid evaluation order is A.i, P.i, process P to get P.s, Q.i, process Q to get Q.s, then A.s. In A→XY, X.i needs Y.s even though Y is on X’s right, violating the restriction. Y.i’s use of X.s would be allowed by itself; it does not rescue the first dependency.

Derivation and answer

Rule1 computes each inherited attribute from the parent’s inherited attribute and, for Q, a left sibling’s attribute; the parent synthesized attribute can then combine child results. This is L-attributed. Rule2 computes X.i using right sibling Y.s, violating the left-to-right dependency restriction. Only Rule1, B.

Original paper, page 11 · Answer key

1 mark · MCQ
Report issue

Which derivation an LR parser reconstructs

Parsing & Syntax Analysis

Question 3, GATE 2019: An LR parser corresponds to which derivation order? Choices: A leftmost; B leftmost in reverse; C rightmost; D rightmost in reverse.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Method: distinguish the left-to-right scan of the input from the order of grammar productions reconstructed by reductions.

1. LR parsing is bottom-up. A reduction replaces a handle, a right-hand side of a production, by its left-hand-side nonterminal.
2. This operation undoes a production application rather than applying it from the start symbol outward. Therefore the derivation is reconstructed in reverse.
3. The handles reduced by an LR parser are exactly those obtained by reversing a rightmost derivation. For example, with S → AB, A → a, B → b, a rightmost derivation is S ⇒ AB ⇒ Ab ⇒ ab. Reversing it gives ab ⇒ Ab ⇒ AB ⇒ S, the bottom-up reduction sequence.
4. In the name LR, L denotes scanning input left-to-right and R denotes reconstructing a rightmost derivation. The L does not mean leftmost derivation.

Result: D, a rightmost derivation in reverse.

Original paper, page 4 · Answer key

1 mark · NAT
Report issue

FOLLOW(B) with a nullable suffix

Parsing & Syntax Analysis

Question 19, GATE 2019: The grammar is S→Aa, A→BD, B→b|ε, D→d|ε. Symbols a,b,d,$ have indices 3,2,1,0 respectively. Find FOLLOW(B), then concatenate its symbol indices in descending order.
Tap to enlarge
Answer & solution

Official answer: 31

Step through it (13 steps)

Method: use the rule for a nonterminal followed by a possibly nullable suffix.

1. FOLLOW(B) contains terminals that can appear immediately after B in a sentential form, not the terminals that B itself derives. In A→BD, the suffix following B is D.
2. FIRST(D)={d,ε}. Add its non-epsilon terminal d to FOLLOW(B), because D may produce d immediately after B.
3. D can also disappear via D→ε. In that case whatever follows A also follows B. From S→Aa, the terminal a follows A, so FOLLOW(A)={a}; add a to FOLLOW(B).
4. There are no other occurrences contributing more symbols. In particular, $ follows the start symbol S, but the required terminal a after A prevents $ from propagating to A or B. The symbol b is in FIRST(B), not FOLLOW(B), and ε is never a FOLLOW-set member.
5. Thus FOLLOW(B)={a,d}. Their indices are 3 and 1, already in descending order, so concatenate them as 31.

Result: 31. The language generated from S is {a,ba,da,bda}, which also illustrates that a B occurrence is followed by d or a.

Original paper, page 7 · Answer key

2 marks · MCQ
Report issue

Propagating declaration types

Semantic Analysis & Type Checking

Question 36, GATE 2019: For declarations use D→T L; T→int|float; L→L1 , id|id. T synthesizes the chosen type. Semantic actions include D→TL: X1.type=X2.type and L→L1,id: X3.type=X4.type. Find X1,X2,X3,X4: A (L,T,L1,L), B (T,L,L1,T), C (L,L,L1,T), D (T,L,T,L1).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

1. T reads the type keyword and synthesizes its type value: int for T→int or float for T→float. The identifier list must receive this value from its declaration context.
2. In D→T L, the value flows from sibling T to L. Therefore L.type=T.type, giving X1=L and X2=T. Reversing this assignment would try to obtain the declared type from an untyped identifier list.
3. In L→L1,id, the parent L already has an inherited type. The shorter list L1 must inherit that same type, so L1.type=L.type. Consequently X3=L1 and X4=L.
4. The last identifier also gets L.type through addType; in the base case L→id, the single identifier receives L.type. For example, int a,b passes int from T to the outer list, then to its inner list and to both identifier entries.
5. The requested tuple is (L,T,L1,L), option A. T need not appear directly in recursive list productions: its value has already been propagated into the inherited L attribute.

Original paper, page 12 · Answer key

2 marks · NAT
Report issue

Closure after an LR(0) transition

Parsing & Syntax Analysis

Question 43, GATE 2019: Given augmented grammar S′→S; S→(L)|id; L→L,S|S, let I0=CLOSURE({S′→·S}). How many distinct LR(0) items are in GOTO(I0, '(')? The comma in L→L,S is a terminal.
Tap to enlarge
Answer & solution

Official answer: 5

Step through it (3 steps)

1. An LR(0) item is a production with a dot marking how much has been recognized. Closure adds productions of any nonterminal immediately after a dot, with their dots at the start.
2. I0 contains S′→·S, S→·(L), and S→·id. Only S→·(L) has an opening parenthesis immediately after its dot.
3. GOTO on '(' advances that dot, yielding the kernel item S→(·L). Its dot precedes L, so add L→·L,S and L→·S.
4. The first of these new items again has L after its dot, but adding L's productions repeats existing items. The second has S after its dot, so add S→·(L) and S→·id.
5. The last two dots precede terminals, so closure stops. The complete set is {S→(·L), L→·L,S, L→·S, S→·(L), S→·id}: exactly 5 items.
6. Do not carry S′→·S into this destination merely because it was in I0. GOTO keeps shifted matching items and then their closure, not the entire starting state.

Original paper, page 14 · Answer key

1 mark · MCQ
Report issue

Compiler phase ordering

Compiler Phases, Linking & Loading

Question 8, GATE 2018: Choose the false claim: A CFGs can specify lexical and syntactic rules; B type checking precedes parsing; C high-level code can translate to different intermediate representations; D function arguments can be passed on the program stack.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Method

Parsing identifies constructs such as expressions, declarations and function calls. Type checking applies rules to those constructs and their symbol-table information, so the conventional dependency is syntax before semantic type checking. A compiler may interleave actions during parsing, but that does not establish the blanket claim in B. Regular token languages are also context-free, which is why A is expressively valid even though practical lexers usually use regular expressions.

Solution

Parsing supplies the syntactic structure on which conventional type checking operates, so saying type checking is performed before parsing is false, B. CFGs can express regular lexical rules as well as syntax, multiple intermediate representations are possible, and stack argument passing is standard.

Original paper, page 5 · Answer key

2 marks · MCQ
Report issue

Longest-prefix lexical analysis

Lexical Analysis

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

Official answer: D

Method

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

Solution

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

Original paper, page 15 · Answer key

2 marks · MCQ
Report issue

Reading precedence from a parse tree

Parsing & Syntax Analysis

Question 38, GATE 2018: For a#b$c$d#e#f, the supplied tree represents a#(((b$c)$d)#(e#f)). Choose A $ higher and left-associative, # right-associative; B # higher and left-associative, $ right-associative; C $ higher and left-associative, # left-associative; D # higher and right-associative, $ left-associative.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Method

Read each internal node as an operation on its two child subtrees. The $ subtree first combines b,c and then combines that result with d, demonstrating left association. Treating this whole subtree as one operand gives a#(X#(e#f)), which nests # to the right. Because the dollar chain is grouped into an operand before surrounding hash operations, $ has higher precedence in the intended grammar. Do not infer precedence from the visual height of leaf letters.

Solution

The tree groups the expression as a#(((b$c)$d)#(e#f)). The two dollar operations group left, and their subtree is below the hash operations, showing higher precedence. The hash chain groups to the right. Thus A.

Original paper, page 15 · Answer key

1 mark · MCQ
Report issue

Intermediate Code

Question 12, GATE 2017: Convert p=a−b; q=p*c; p=u*v; q=p+q to static single assignment form. Options: A p1=a−b;q1=p1*c;p1=u*v;q1=p1+q1. B p3=a−b;q4=p3*c;p4=u*v;q5=p4+q4. C p1=a−b;q1=p2*c;p3=u*v;q2=p4+q3. D p1=a−b;q1=p*c;p2=u*v;q2=p+q.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

1. SSA requires each defined variable version to have exactly one assignment. Subscripts need not start at 1, but every use must refer to the correct reaching definition.

2. First create p3=a−b; then q4=p3*c must use that version. The reassignment p=u*v needs a different version, p4.

3. The last sum uses new p and old q: q5=p4+q4. This is option B. A repeats definitions, C uses undefined versions, and D leaves unversioned references.

Original paper, page 7 · Answer key

1 mark · MCQ
Report issue

Parsing & Syntax Analysis

Question 17, GATE 2017: Grammar: P→xQRS; Q→yz | z; R→w | ε; S→y. Find FOLLOW(Q). A {R}; B {w}; C {w,y}; D {w,$}.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Step through it (13 steps)

1. FOLLOW(Q) contains terminal symbols that can occur immediately after a derivation of Q, not the next nonterminal’s name. Its only occurrence is in P→xQRS.

2. R can produce w, placing w immediately after Q. It can also disappear through ε, exposing S, which produces y.

3. S is not nullable, so Q never reaches the end of this production and no end marker is inherited. FOLLOW(Q)={w,y}, C.

Original paper, page 10 · Answer key

2 marks · NAT
Report issue

Intermediate Code

Question 43, GATE 2017: Grammar: stmt→if expr then expr else expr; stmt | δ; expr→term relop term | term; term→id | number; id→a|b|c; number→[0–9]. δ is the empty statement and relop a relational operator. A program contains ten if terminals. Find its number of control-flow paths, counting the two branches of one if as two paths.
Tap to enlarge
Answer & solution

Official answer: 1024.0

Our answer: 1024

1. The stmt grammar appends one if statement followed by another stmt. Thus ten if terminals describe ten sequential binary choices, not a nesting with an unspecified shape.

2. After the first if there are two structural paths. Each subsequent if doubles the existing path count because every current path can take either its then or else branch.

3. Therefore P0=1 and Pn=2Pn−1, giving P10=210=1024. This counts syntactic control-flow graph paths, as the question’s example does; repeated or constant conditions can make some paths infeasible for actual executions.

Original paper, page 19 · Answer key

2 marks · NAT
Not in GATE 2027 syllabusReport issue

Code Generation & Register Allocation

Question 52, GATE 2017: For (a−1)*(((b+c)/3)+d), find minimum registers for optimal load/store code generation without spills. Only loads/stores can access memory; arithmetic operands must be registers or immediate constants.
Tap to enlarge
Answer & solution

Official answer: 2.0

Our answer: 2

1. Evaluate the more demanding right subtree first. Load b into R1 and c into R2; add into R1. Divide R1 by immediate 3, then reuse R2 to load d and add it to R1. Now R1 holds ((b+c)/3)+d.

2. Keep R1 live and load a into R2. Subtract immediate 1 from R2, then multiply R2 and R1 into either register. At no time are more than two registers live, and no intermediate is stored to memory.

3. One register cannot perform b+c under the stated arithmetic rule because both non-immediate operands must be in registers simultaneously. Hence both lower and upper bounds are 2.

Original paper, page 23 · Answer key

1 mark · MCQ
Report issue

Compiler Phases, Linking & Loading

Question 5, GATE 2017: Match compiler inputs P:syntax tree, Q:character stream, R:intermediate representation, S:token stream with phases i:code generator, ii:syntax analyzer, iii:semantic analyzer, iv:lexical analyzer. Options (P,Q,R,S): A:(ii,iii,iv,i), B:(ii,i,iii,iv), C:(iii,iv,i,ii), D:(i,iv,ii,iii).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

1. Follow the compiler pipeline from source text. The lexical analyzer reads characters and groups them into tokens, so Q→iv. The syntax analyzer reads those tokens and recognizes grammatical structure, so S→ii.

2. Semantic analysis then uses the syntax tree to check matters such as declarations, types, and compatible operations; hence P→iii.

3. After front-end processing and intermediate-code construction, the code generator translates the intermediate representation into target code, giving R→i. In the requested P,Q,R,S order the mapping is (iii,iv,i,ii), option C. Do not confuse a phase's output with its input.

Original paper, page 3 · Answer key

1 mark · MCQ
Report issue

Parsing & Syntax Analysis

Question 6, GATE 2017: Which parser-power statements are correct? I:Canonical LR is more powerful than SLR. II:SLR is more powerful than LALR. III:SLR is more powerful than canonical LR. A:I only. B:II only. C:III only. D:II and III.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

1. Power here refers to the class of grammars handled without parsing conflicts, with the usual one-symbol lookahead versions. The inclusion chain is SLR(1) ⊂ LALR(1) ⊂ canonical LR(1).

2. SLR uses coarse FOLLOW sets for reductions. Canonical LR uses item-specific lookahead information; LALR merges compatible LR state cores and retains more discrimination than SLR but can lose some canonical LR power.

3. Thus canonical LR can handle every SLR grammar and some additional grammars, making I true. II and III reverse the inclusion direction and are false. Choose A. This comparison is about grammar recognition capability, not parser speed or table size.

Original paper, page 3 · Answer key

2 marks · MCQ
Report issue

Parsing & Syntax Analysis

Question 32, GATE 2017: Grammar G is E→E−T|T, T→T+F|F, F→(E)|id. Choose an equivalent grammar without left recursion. A:the same grammar. B:E→TE′, E′→−TE′|ε, T→T+F|F, F→(E)|id. C:E→TX, X→−TX|ε, T→FY, Y→+FY|ε, F→(E)|id. D:E→TX|(TX), X→−TX|+TX|ε, T→id.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

1. Apply the standard direct-left-recursion transformation A→Aα|β becomes A→βA′, A′→αA′|ε. For E, α is −T and β is T, giving E→TX and X→−TX|ε.

2. Apply it separately to T: α is +F and β is F, giving T→FY and Y→+FY|ε. Keep F→(E)|id so arbitrarily nested factors remain possible. These are exactly option C.

3. A leaves both original recursions intact. B fixes E but leaves T→T+F directly left-recursive. D restricts T to id and cannot generate nested expressions such as ((id)) or parentheses as arbitrary factors. The transformation preserves the generated strings, although semantic associativity must be handled when constructing evaluation actions.

Original paper, page 12 · Answer key

1 mark · NAT
Report issue

Intermediate Code

Question 19, GATE 2016: Find the minimum total number of variable names in static single-assignment form for this straight-line code, including incoming variables:
x=u−t;
y=x*v;
x=y+w;
y=t−z;
y=x*y;
Tap to enlarge
Answer & solution

Official answer: 10.0 : 10.0

Our answer: 10

The five incoming values u, t, v, w, z each need one name. The two definitions of x and three of y need five distinct SSA names: x1=u−t; y1=x1*v; x2=y1+w; y2=t−z; y3=x2*y2. Total 5+5=10 variables, counting incoming values as requested.

In SSA, each name has exactly one definition, but it can be read many times. Hence the two reads of t share one incoming name, while the successive writes to y cannot share a name. When renaming, every use must refer to its most recent preceding definition: the final product uses x2 and y2, not the original names. There are no branches here, so no φ-functions are necessary. Five new defined names plus five distinct incoming names is the requested total.

Original paper, page 9 · Answer key

2 marks · MCQ
Report issue

Runtime Environments & Parameter Passing

Question 36, GATE 2016: Assume dynamic scoping and pass-by-reference in this pseudocode:
a=3;
void n(x){x=x*a;print(x);}
void m(y){a=1;a=y−a;n(a);print(a);}
void main(){m(a);}
What is printed? A:6,2. B:6,6. C:4,2. D:4,4. The source does not explicitly declare whether m's first assignment introduces a local a; preserve that ambiguity.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Our answer: D under implicit local-a binding

The intended pseudocode treats a=1 inside m as introducing a local a, while reference parameter y remains an alias of the outer a=3. Then local a=y−a=2. Passing it by reference to n makes x and dynamically resolved a refer to that same local cell: x=x*a stores 4, and both prints show 4, D. If a=1 instead assigns the existing outer dynamically scoped a, y aliases it, so a=y−a becomes 0 and the output is 0, 0. The source lacks an explicit local declaration, so its binding convention must be supplied.

Distinguish parameter aliasing from name lookup. Under the intended local-binding interpretation, y aliases the global cell containing 3, while m's local a first contains 1 and then 2. n's formal x aliases that local cell, and dynamic lookup of its free name a finds the active m frame, also that same cell. Thus the assignment squares 2 in place. Under assignment-to-existing-binding semantics both y and a refer to the global cell before subtraction, making 1−1=0. The printed key chooses the former semantics but does not remove the source ambiguity.

Original paper, page 15 · Answer key

2 marks · NAT
Report issue

Parsing & Syntax Analysis

Question 45, GATE 2016: Three binary operators have these language-specific rules: + has highest precedence and is left-associative; − has medium precedence and is right-associative; * has lowest precedence and is left-associative. Evaluate 2−5+1−7*3.
Tap to enlarge
Answer & solution

Official answer: 9.0 : 9.0

Our answer: 9

Addition has highest precedence, giving 5+1=6. The remaining subtraction is right-associative, so 2−6−7 groups as 2−(6−7)=3. Multiplication has lowest precedence, producing 3*3=9.

Insert parentheses in precedence order before calculating: the expression becomes (2−(5+1)−7)*3, then right associativity changes the subtraction part to 2−((5+1)−7). The inner result 6−7 is−1, so the outer result is 3 and multiplying by 3 gives 9. Ordinary arithmetic precedence would put multiplication first and produce a different result; this question intentionally defines a different expression grammar.

Original paper, page 17 · Answer key

2 marks · MCQ
Report issue

Semantic Analysis & Type Checking

Question 46, GATE 2016: A syntax-directed translation scheme has S→aA {print 1}, S→a {print 2}, A→Sb {print 3}. A bottom-up parser processes input aab. What is the output? A:1 3 2. B:2 2 3. C:2 3 1. D:syntax error.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Step through it (8 steps)

Bottom-up parsing of aab first reduces the second a by S→a, printing 2. Then Sb reduces to A, printing 3. Finally aA reduces to S, printing 1. The action order is 2, 3, 1, option C.

Reduction order follows a rightmost derivation in reverse, not the textual order in which productions are listed. A valid derivation is S⇒aA⇒aSb⇒aab. Reversing those steps first collapses the second a into S, then Sb into A, then aA into S. Each semantic action is at the end of its production, so it runs at the corresponding reduction and emits 2,3,1. The successful derivation also rules out syntax error.

Original paper, page 18 · Answer key

1 mark · MCQ
Report issue

Compiler Phases, Linking & Loading

Question 19, GATE 2016: Match P lexical analysis, Q top-down parsing, R semantic analysis, S runtime environments with i leftmost derivation, ii type checking, iii regular expressions, iv activation records. A P-i,Q-ii,R-iv,S-iii; B P-iii,Q-i,R-ii,S-iv; C P-ii,Q-iii,R-i,S-iv; D P-iv,Q-i,R-ii,S-iii.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Lexical analysis uses regular expressions; top-down parsing constructs a leftmost derivation; semantic analysis checks types; runtime environments organize activation records. Hence P-iii, Q-i, R-ii, S-iv, B.

A lexer recognizes tokens such as identifiers and numbers from character patterns. A top-down parser expands the leftmost pending nonterminal toward the input. Semantic analysis rejects type-incompatible expressions even when their syntax parses. Activation records store each call’s parameters, locals and return information at runtime; this separates all four roles.

Original paper, page 30 · Answer key

2 marks · MCQ
Report issue

Parsing & Syntax Analysis

Question 45, GATE 2016: Which grammar has no left recursion? A S→AB,A→Aa|b,B→c; B S→Ab|Bb|c,A→Bd|ε,B→e; C S→Aa|B,A→Bb|Sc|ε,B→d; D S→Aa|Bb|c,A→Bd|ε,B→Ae|ε.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Grammar B has an acyclic nonterminal dependency chain S→A/B, A→B, with B deriving only terminal e; it cannot derive a sentential form beginning again with the same nonterminal. A has direct A→Aa. C has S⇒Aa⇒Sca. D has A⇒Bd⇒Aed. Thus B alone is free of left recursion.

Left recursion means a derivation A⇒+Aα, possibly passing through other nonterminals and nullable productions. It is not the same as any recursion anywhere on a right side. In B every chain beginning in a nonterminal descends from S to A to B, and B immediately produces terminal e, so no cycle can return to its starting nonterminal.

Original paper, page 38 · Answer key

2 marks · MCQ
Report issue

Parsing & Syntax Analysis

Question 46, GATE 2016: Two grammars describe C-like declarations with at least one array dimension, e.g. int a[10][3];. Terminals: int, ;, id, [, ], num. G1: D→int L;, L→id [E, E→num] | num][E. G2: D→int L;, L→id E, E→E[num] | [num]. Which correctly generate the declarations? A both; B G1 only; C G2 only; D neither.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

G1 emits the opening bracket with id, then its recursive E→num][E adds each completed dimension and the next opening bracket, ending with E→num]. G2 emits one or more bracketed num groups through left recursion E→E[num] with base[num]. Both generate int id[num]...[num]; with at least one dimension, including the example. Thus A.

For two dimensions, G1 derives L⇒id [E⇒id [num][E⇒id [num][num]. G2 derives L⇒id E⇒id E[num]⇒id [num][num]. Substituting id=a and the two num tokens by 10 and 3 yields the example in each. Left recursion may inconvenience a parser, but it does not make the generated language incorrect.

Original paper, page 39 · Answer key

1 mark · MCQ
Report issue

Parsing & Syntax Analysis

Question 18, GATE 2015: At any valid shift-reduce parsing state, which is true? A viable prefixes appear only at the stack bottom, not inside; B only at its top, not inside; C the stack contains only a set of viable prefixes; D it never contains viable prefixes.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

A handle is the portion reduced in a reverse rightmost derivation. A viable prefix stops at or before the right end of such a handle. The parser stack's grammar symbols form one viable prefix, and each initial segment of those symbols is also viable. Read the paper's “set” wording in this prefix sense, not as a claim that arbitrary internal substrings or LR state numbers are grammar prefixes.

Solution: The grammar-symbol portion of a shift-reduce stack is a viable prefix: a prefix of a right-sentential form that does not pass the handle’s right end. Taking a shorter prefix cannot cross that end, so every prefix is viable too. Thus C.

Original paper, page 8 · Answer key

2 marks · MCQ
Report issue

Code Optimization & Data-Flow Analysis

Question 46, GATE 2015: A variable is live at statement Si if some reachable use Sj has no intervening assignment, including Si and Sj. CFG: block 1 p=q+r; s=p+q; u=s*v; branches to block 2 v=r+u or block 3 q=s*u; both go to block 4 q=v+r; block 4 loops to block 1. Which are live at both block 2 and block 3 entry? A p,s,u; B r,s,u; C r,u; D q,v.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Use the old value test: a value matters only if a path reads it before replacement. At block 2, r and u are read immediately; old v is killed by v=r+u, old q by block 4, and p,s by block 1 before future use. At block 3, s,u are immediate reads and v,r remain needed at block 4. Taking the intersection of {r,u} and {s,u,v,r} leaves {r,u}. Liveness is backward data flow and uses possible paths, not just values read in the next line.

Solution: At entry to block 2, r and u are used by v=r+u; old v is overwritten and old q is overwritten in block 4. At entry to block 3, s and u are used by q=s*u, while v and r are needed by block 4. Thus live-in sets are{r, u} and{s, u, v, r}; their intersection is{r, u}, C. Values overwritten in block 1 before any later use need not be added.

Original paper, page 17 · Answer key

2 marks · NAT
Report issue

Intermediate Code

Question 47, GATE 2015: Find the least temporary-variable count for static-single-assignment three-address code for q+r/3+s−t*5+u*v/w.
Tap to enlarge
Answer & solution

Official answer: 8

One valid translation is t1=r/3; t2=q+t1; t3=t2+s; t4=t*5; t5=t3−t4; t6=u*v; t7=t6/w; t8=t5+t7. There are eight binary-operation nodes and each three-address instruction computes only one. SSA forbids assigning a later intermediate into an already used temporary name, so the intended unoptimized translation needs eight names, including its final result. Reusing one scratch register would not be SSA.

Solution: The expression has eight binary operations: the divisions r/3 and (u*v)/w, multiplications t*5 and u*v, and four outer additive/subtractive operations. A three-address translation with a fresh temporary for every operation therefore uses eight temporaries, including the expression result.

Original paper, page 17 · Answer key

1 mark · MCQ
Report issue

Compiler Phases, Linking & Loading

Question 27, GATE 2015: Match P lexical analysis, Q parsing, R register allocation, S expression evaluation with 1 graph colouring, 2 DFA minimization, 3 postorder traversal, 4 production tree. A P2Q3R1S4; B P2Q1R4S3; C P2Q4R1S3; D P2Q3R4S1.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Lexical analysis uses minimized DFAs; parsing constructs production/parse trees; register allocation uses interference-graph coloring; expression evaluation visits operands before operators in postorder. Therefore P-2, Q-4, R-1, S-3, C.

Lexical patterns are recognized by finite automata, which can be minimized without changing recognized tokens. Parsing uses grammar productions organized into a parse tree. Register-allocation interference graphs put simultaneously live variables at adjacent vertices, so colouring assigns nonconflicting registers. To evaluate an expression tree, children must be evaluated before their operator parent, which is postorder. Combining all four gives the single complete matching C.

Original paper, page 35 · Answer key

1 mark · MCQ
Report issue

Intermediate Code

Question 28, GATE 2015: About AST and CFG, which is true? A successors always correspond to later source code; B neither can contain a cycle; C maximum successors can depend on input program; D each node corresponds to at most one statement.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

AST node arity can vary with program constructs, and CFG successor counts can vary with multiway branches such as switch. Thus C under the general AST/basic-block CFG representation. CFGs can contain loop cycles, successors need not follow source order, and a basic block can contain several statements.

An AST can represent a construct with a variable number of operands or children, while a CFG can give a multiway branch many successor blocks. Thus a fixed universal successor count does not follow from the general names. CFG loop back-edges directly disprove B, and also disprove A’s assumption that all successors appear later in source. A basic-block CFG node can contain several sequential statements, disproving D. Different fixed-arity normalized intermediate representations are possible, but are not specified here.

Original paper, page 35 · Answer key

2 marks · MCQ
Report issue

Intermediate Code

Question 44, GATE 2015: Intermediate code:1 i=1; 2 j=1; 3 t1=5*i; 4 t2=t1+j; 5 t3=4*t2; 6 t4=t3; 7 a[t4]=−1; 8 j=j+1; 9 if j≤5 goto 3; 10 i=i+1; 11 if i<5 goto 2. CFG node/edge counts using entry/exit nodes: A5, 7; B6, 7; C5, 5; D7, 8.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Our answer: B with explicit entry and exit nodes

Leaders split the code into blocks[1], [2], [3..9], [10..11]. Add separate entry and exit nodes: 6 nodes. Edges are entry→B1, B1→B2, B2→B3, B3→B3, B3→B4, B4→B2, B4→exit: 7. Thus B. Without explicit entry/exit nodes, counts differ; the official choice uses them.

Leaders are statement 1, start 2(target of 11), start 3(target of 9), and 10(after conditional 9). Group straight-line instructions until each branch: B1=[1], B2=[2], B3=[3…9], B4=[10…11]. B3 has a self-loop when j≤5 and a fallthrough to B4; B4 returns to B2 when i<5 and otherwise exits. Add entry→B1, B1→B2, B2→B3 and the two B4 edges: seven edges over four blocks plus entry/exit=6 nodes. State the node-count convention rather than hiding these extra nodes.

Original paper, page 41 · Answer key

1 mark · MCQ
Report issue

Parsing & Syntax Analysis

Question 15, GATE 2015: Among simple LR (SLR), canonical LR and look-ahead LR (LALR), identify, in order, the easiest method to implement and the most powerful method. Options: (A) SLR, LALR; (B) canonical LR, LALR; (C) SLR, canonical LR; (D) LALR, canonical LR.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

1. SLR uses one FOLLOW set for all reductions of a nonterminal, whereas canonical LR keeps the lookahead specific to each item/context. LALR merges compatible LR states for smaller tables but may introduce conflicts that canonical LR avoids.

2. SLR uses LR(0) states plus FOLLOW sets and is the simplest of the three. Canonical LR(1) retains item-specific lookaheads and recognizes the broadest grammar class. Thus SLR, canonical LR, C.

Original paper, page 58 · Answer key

2 marks · MCQ
Report issue

Parsing & Syntax Analysis

Question 65, GATE 2015: Grammar G has productions S→F|H, F→p|c, H→d|c. S,F,H are nonterminals; p,d,c are terminals. Assess S1: LL(1) can parse all strings generated using grammar G; S2: LR(1) can parse all strings generated using grammar G. Options: (A) S1 only; (B) S2 only; (C) both; (D) neither. The question concerns this grammar, not whether its language has a different LL(1) or LR(1) grammar.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Step through it (3 parts)

1. The string c has two parse trees: S→F→c and S→H→c.

2. Thus the displayed grammar is ambiguous and is neither LL(1) nor LR(1). Concretely FIRST(F) and FIRST(H) both contain c, causing an LL conflict; after shifting c, completed F→c and H→c items both reduce on end-of-input, causing an LR reduce/reduce conflict. Therefore D for parsing with this grammar. Its finite language can of course be represented by a different unambiguous grammar S→p|d|c.

Original paper, page 79 · Answer key

1 mark · MCQ
Report issue

Code Optimization & Data-Flow Analysis

Question 17, GATE 2014: Which compiler statement is false? A: A basic block is entered at its beginning and exited at its end. B: Available-expression analysis supports common-subexpression elimination. C: Live-variable analysis supports dead-code elimination. D: Replacing x=4*5 by x=20 is common-subexpression elimination.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

1. Method and setup. Common-subexpression elimination reuses a previously computed expression whose operands have not changed. Here no prior computation is being reused: a constant expression is evaluated during compilation. Available-expression and liveness analyses instead answer whether a value is reusable and whether a computed result will be needed.

2. Work through the result and its assumptions. Replacing the compile-time arithmetic 4×5 by 20 is constant folding, not common-subexpression elimination. The other statements describe standard basic-block and dataflow uses. Thus the false statement is D.

Original paper, page 11 · Answer key

2 marks · MCQ
Report issue

Parsing & Syntax Analysis

Question 34, GATE 2014: An LR item set contains S→L·>R and Q→R·. On lookahead/input symbol <, does it contain a conflict? A: both shift-reduce and reduce-reduce. B: shift-reduce only. C: reduce-reduce only. D: neither. The symbol after the first dot is >, while the queried input is <.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

1. Method and setup. A shift is possible only for a terminal immediately after a dot, and a reduction only for a completed item, subject to the parser’s lookahead rules. Do not confuse the literal terminals < and >. There is only one completed item, so no pair of competing reductions is present.

2. Work through the result and its assumptions. The first item has its dot before >, not before <. Thus no shift is enabled on <. Only Q→R. is completed, so at most one reduction is possible on that symbol. There is neither a shift-reduce nor reduce-reduce conflict, D.

Original paper, page 15 · Answer key

1 mark · MCQ
Report issue

Parsing & Syntax Analysis

Question 17, GATE 2014: Grammar: S→T*P; T→U or T*U; P→Q+P or Q; Q→Id; U→Id. Which associativity statement is true? A + left, * right; B + right, * left; C both right; D both left.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

1. Set up the reasoning. Inspect the recursive side of each operator production. T recurs on the left of *, while P recurs on the right of +.

2. Derive the result. The rule T→T*U is left-recursive and groups multiplication to the left. P→Q+P is right-recursive and groups addition to the right. Thus + is right associative and * left associative, B.

3. Check the interpretation. Expanding T twice gives (Id*Id)*Id, whereas expanding P twice gives Id+(Id+Id). Associativity concerns grouping of repeated operators, not which operator has greater precedence.

Original paper, page 33 · Answer key

1 mark · MCQ
Report issue

Compiler Phases, Linking & Loading

Question 18, GATE 2014: Which is not performed during compilation of a program? A dynamic memory allocation; B type checking; C symbol-table management; D inline expansion.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

1. Set up the reasoning. Distinguish work done on the source representation by a compiler from operations performed by the compiled program when it runs. A dynamic allocation creates runtime objects whose sizes or lifetimes may depend on execution.

2. Derive the result. Allocation of the running program’s dynamic objects occurs at runtime. Type checking, symbol-table construction and inline expansion are compiler tasks. Thus A. A compiler may itself allocate memory while running, but that is not the intended meaning of program dynamic allocation.

3. Check the interpretation. The compiler may emit allocation calls and itself allocate memory while compiling; those facts do not make allocation of the target program's runtime objects a compilation phase. Type checks, names, and inlining are standard compile-time concerns.

Original paper, page 33 · Answer key

2 marks · MCQ
Report issue

Intermediate Code

Question 34, GATE 2014: A compiler accesses X[i][j][k] using byte-offset code t0=i*1024; t1=j*32; t2=k*4; t3=t1+t0; t4=t3+t2; t5=X[t4]. Integers are 32 bits, characters 8 bits. Which declaration matches? A int X[32][32][8]; B int X[4][1024][32]; C char X[4][32][8]; D char X[32][16][2].
Tap to enlarge
Your answer
Answer & solution

Official answer: A

1. Set up the reasoning. For a row-major three-dimensional array with element size e and trailing dimensions d2,d3, the offset is e·(i·d2·d3+j·d3+k). Match its three coefficients to the generated code.

2. Derive the result. The byte strides show 4-byte int elements, 8 elements in the last dimension(32/4), and 32 in the middle dimension(1024/32). The first dimension is not recoverable from strides alone, but among the listed declarations only int X[32][32][8] matches. Thus A.

3. Check the interpretation. The innermost coefficient identifies e=4 bytes; j then gives d3=8 and i gives d2=32. The leading dimension is not encoded in these strides, so select the matching offered declaration without claiming that 32 as its first dimension was derived.

Original paper, page 38 · Answer key

1 mark · MCQ
Report issue

Code Optimization & Data-Flow Analysis

Question 17, GATE 2014: Which is a purpose of intermediate code in a compiler? A simplify parsing and semantic analysis; B improve error recovery/reporting; C increase reuse of a machine-independent optimizer across compilers; D improve register allocation.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Step 1: Separate a compiler into a source-language front end, an optimizer and a target-machine back end. A shared intermediate representation gives the middle portion a common input/output language. Step 2: The same machine-independent optimization passes can then be used for several source languages or machine targets. This directly explains C. Step 3: Parsing and semantic analysis are primarily front-end tasks, and register allocation is a later target-related task. Intermediate code may assist a design, but the other choices do not state its principal reuse motivation.

Original paper, page 56 · Answer key

1 mark · MCQ
Report issue

Runtime Environments & Parameter Passing

Question 18, GATE 2014: Evaluate: (1) statically allocating every data area prevents recursion; (2) automatic garbage collection is essential for recursion; (3) dynamic allocation of activation records is essential for recursion; (4) both heap and stack are essential for recursion. Choose A 1,2 only; B 2,3 only; C 3,4 only; D 1,3 only.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Our answer: D under the general recursion storage model

Step 1: General recursive calls can leave multiple invocations of the same procedure simultaneously active. Each needs its own parameters, local variables, return address and other activation information. Step 2: One fixed static record per procedure cannot preserve all these activations; records must be allocated as calls occur. This is the intended sense in which 1 and 3 hold. Step 3: A runtime stack allocates and reclaims activation records without a heap or automatic garbage collector, refuting 2 and 4. Thus D. Bounded recursion or tail-call elimination can use fixed storage, so these claims concern the conventional general recursion model, not every special recursive program.

Original paper, page 57 · Answer key

2 marks · MCQ
Report issue

Code Optimization & Data-Flow Analysis

Question 34, GATE 2014: The basic block executes a=b+c; c=a+d; d=b+c; e=d−b; a=e+b. What are the minimum DAG node and edge counts? A (6,6); B (8,10); C (9,12); D (4,4).
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Our answer: A with algebraic simplification

Step 1: Preserve old values when tracking assignments: let the input leaves be b0,c0,d0. The first three operations create u=b0+c0, v=u+d0, w=b0+v. The current c is v and current d is w. Step 2: Algebraically, e=w−b0=(b0+v)−b0=v, and final a=e+b0=v+b0=w. Therefore e shares v's node and a shares w's node. Step 3: The minimized DAG has three input leaves and three binary addition nodes: six nodes. Each operation has two incoming operand edges, giving six edges, A. Without cancellation, a purely syntactic DAG gives eight nodes and ten edges. The keyed minimum assumes valid algebraic identities, not unrestricted floating-point cancellation.

Original paper, page 60 · Answer key

1 mark · MCQ
Report issue

Reduction-count production terminology

Parsing & Syntax Analysis

Question 9, GATE 2013: A bottom-up parser processes n tokens using a grammar with no epsilon or “unit” productions, expressly described in the source as A→ε and A→a. What is the maximum number of reductions? A n/2; B n−1; C2n−1; D2^n.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Our answer: B under the displayed no-single-symbol-production interpretation

A reduction with a right-hand side of length at least 2 decreases the stack/sentential length by at least 1. Starting with n terminals and ending with one start symbol thus allows at most n−1 such reductions, attained by binary reductions, giving B. However the source calls A→a a unit-production, whereas standard CFG terminology reserves unit-production for A→B with B a nonterminal. If only standard unit rules and epsilon rules are forbidden, terminal rules A→a remain, and a Chomsky-normal-form derivation can require n terminal reductions plus n−1 binary reductions=2n−1. The key therefore relies on the source’s intended ban on length-one reductions, not the usual terminology alone.

Each reduction replaces a right-hand side by one nonterminal. If every permitted right-hand side has at least two symbols, each reduction shrinks the total length by at least one. Reducing n tokens to one start symbol then permits at most n−1 reductions; a binary parse tree attains that many internal combinations. The caveat is not optional: a normal terminal production A→a has length 1 and would add reductions without shortening the string. The printed parenthetical explicitly rules those out, even though it uses nonstandard “unit” terminology.

Original paper, page 3 · Answer key

2 marks · MCQ
Report issue

Merging LR items for LALR parsing

Parsing & Syntax Analysis

Question 40, GATE 2013: Two LR(1) states have items X→c·X, X→·cX, X→·d; first has lookaheads c/d on all, second $. About merging them into LALR, which claims are false?1 cannot merge because lookaheads differ;2 merging creates shift/reduce conflict;3 merging creates reduce/reduce conflict;4 cannot merge because goto on c leads to different states. A1 only, B2 only, C1and4, Dallfour.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

The two LR(1) states have the same LR(0) core, so LALR construction merges them and unions the lookahead sets for each core item. Every displayed item still has symbols to the right of the dot. Consequently this merged state has no reduction action and can create neither a shift/reduce nor a reduce/reduce conflict there. Its equal-core goto states are likewise merged in the LALR construction. Each of the four asserted objections is false, so D.

LALR equivalence compares items after removing lookaheads, and the two displayed sets then match exactly. Unioning lookaheads gives{c, d,$} for each item. Shift actions depend on the symbol after the dot; none of these items has its dot at the end, so there is no reduce action to conflict with a shift or another reduction. Goto targets with equal cores are treated by the same merging rule. Different lookaheads and different original state numbers are not reasons to reject the merge.

Original paper, page 9 · Answer key

2 marks · MCQ
Report issue

Reference parameter and multiplication evaluation order

Runtime Environments & Parameter Passing

Question 42, GATE 2013: p starts 5. The function uses reference parameter x and value parameter c: int f(int &x, int c){c=c−1;if(c==0)return1;x=x+1;return f(x, c)*x;} What does f(p, p) return? A3024, B6561, C55440, D161051. The published key awards Marks to All; source does not specify operand evaluation order.
Tap to enlarge
Your answer
Answer & solution

Official answer: Marks to All

Our answer: No uniquely specified value; 3024 (A) and 6561 (B) arise from different operand orders.

The parameter declaration int &x is C++ reference syntax, not valid C. Every recursive invocation aliases the same p through x, whereas c is a private by-value copy. The four non-base calls increment p successively to 6, 7, 8 and 9; the fifth call returns 1 without incrementing p. In return f(x, c) * x, multiplication does not require the left operand to be evaluated first. If each call reads its right-hand x before executing the recursive call, the stored factors are 6, 7, 8, 9 and the return value is 6×7×8×9=3024 (A). If each call executes the recursive call before reading its right-hand x, all four factors are the final p=9 and the result is 9^4=6561 (B). Mixed choices can give other values. Under C++ rules sequencing a function’s execution as a unit relative to otherwise unsequenced outside evaluations, this is an unspecified operand-order issue; the recursive function call must not be confused with an unsequenced x++ written directly beside a read of x. The source does not prescribe an evaluation convention or a language version, so no unique numerical option follows. The official Code A key explicitly awards Marks to All. This record is classified under compiler parameter-passing/evaluation semantics, not as a valid C program.

Make the parameter environments explicit: each call has its own c, but every x refers to the same external p. The nonbase frames correspond to c after decrement 4, 3, 2, 1. Each increments p once, so p becomes 9 at the base return. A frame can fetch its multiplication operand before recursion, preserving its current 6, 7, 8or9, or fetch after recursion, seeing9. Thus a single deterministic answer requires an evaluation-order convention absent from the prompt. The official MTA must remain an adjudication label, not be replaced by whichever value one compiler happens to print.

Original paper, page 10 · Answer key

2 marks · MCQ
Not in GATE 2027 syllabusReport issue

Minimum register spills with code motion

Code Generation & Register Allocation

Question 48, GATE 2013: Register-only processor allows at most 2 source operands and 1destination. Code: c=a+b;d=c*a;e=c+a;x=c*c;if(x>a){y=a*a;}else{d=d*d;e=e*e;}. All variables dead after segment. With only 2 registers and code motion as the only optimization, minimum spills to memory: A0, B1, C2, D3.
Question 48, GATE 2013: Register-only processor allows at most 2 source operands and 1destination. Code: c=a+b;d=c*a;e=c+a;x=c*c;if(x>a){y=a*a;}else{d=d*d;e=e*e;}. All variables dead after segment. With only 2 registers and code motion as the only optimization, minimum spills to memory: A0, B1, C2, D3.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

One spill store suffices. With registers R1, R2, start with a in R1 and b in R2. Compute R2←R1+R2 (c), store c once in spill slot S, and compute R2←R2×R2 (x). Compare R2 with R1. On the true branch compute y as R1←R1×R1. On the false branch execute: load R2←S; R2←R2×R1 (d); R2←R2×R2 (d²); load R2←S; R2←R2+R1 (e); R2←R2×R2 (e²). The computations d=c*a and e=c+a have been sunk into the false branch, where they are used, and arranged just before their respective squarings. Their former values are unused on the true branch, and all variables are dead after the segment, so this code motion preserves the required values. It performs one spill store and two reloads on the false path; reloads are not additional spills to memory. For the lower bound, after forming c the independent live values a and c already occupy both registers. Before the branch can be decided, at least one of d=c*a, e=c+a or x=c*c must be computed. If d or e is first, its result is needed for its later square while both a and c remain necessary for the other operations. If x is first, x and a are needed for the test while c is still needed on the false path. Thus the first such result forces three simultaneously needed values in a no-spill schedule, regardless of permitted reordering. A live value must be saved. Since recomputation and dead-code elimination are not allowed, zero spills is impossible and the minimum is one, option B.

The spill count in this question counts stores of live register values to memory. It does not count initial operand loads or each subsequent reload as another spill. The construction saves c once, reuses its register for x, then reloads c separately for the two false-branch calculations. Its one-store bound and the three-live-values argument together establish an exact minimum, not just an example. If arbitrary recomputation or elimination of dead code were allowed, the optimization problem would change, which is why the stated restriction matters.

Original paper, page 11 · Answer key

2 marks · MCQ
Not in GATE 2027 syllabusReport issue

Minimum registers without code motion

Code Generation & Register Allocation

Question 49, GATE 2013: For the same code c=a+b;d=c*a;e=c+a;x=c*c;if(x>a)y=a*a;else{d=d*d;e=e*e;}, all variables dead afterward. With original statement order and only register-allocation optimization, how many registers avoid spills? A3, B4, C5, D6.
Question 49, GATE 2013: For the same code c=a+b;d=c*a;e=c+a;x=c*c;if(x>a)y=a*a;else{d=d*d;e=e*e;}, all variables dead afterward. With original statement order and only register-allocation optimization, how many registers avoid spills? A3, B4, C5, D6.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Retain the printed statement order. Immediately after e=c+a and before x=c*c, a is live for the comparison and true branch, c is live for x, and d, e are live for their possible false-branch squarings. Thus {a, c, d, e} is a four-value live set, giving a lower bound of four registers. Four also suffice: R1 holds a throughout the straight-line part; R2 starts as b, is overwritten by c=a+b, then is overwritten by x=c*c once c has had its last use; R3 holds d=c*a and R4 holds e=c+a. The comparison uses R2 and R1. On the true branch, y=a*a can overwrite R1. On the false branch, d² and e² overwrite R3 and R4 respectively. No extra destination register is needed because destinations may alias source registers. Hence the exact minimum is four, option B.

Liveness asks whether a computed value will still be needed on some future path. Before x is computed, a is required for comparison, c for the square, and d/e for the possible false branch. Even though only one branch eventually executes, register allocation cannot discard d/e before the condition is known under the fixed order. Four live values therefore impose four registers. At the next step c has its final use, so x can overwrite its register and no fifth register is needed.

Original paper, page 11 · Answer key

2 marks · MCQ
Report issue

Static links in nested procedure activations

Runtime Environments & Parameter Passing

Question 36, GATE 2012: In a lexically scoped block language, main declares A1 and A2. A1 calls A2. A2 declares A21 and calls A21; A21 calls A1. Main calls A1, producing the live call stack main→A1(first)→A2→A21→A1(second). Which activation-record/access-link diagram is correct? Let M, X, Y, Z, W denote these five activations respectively. Arrows below are access (static) links, and FP denotes the frame pointer.
(A) X→M, Y→X, Z→Y, W→Z; FP=W.
(B) Y→M, Z→Y, W→Z; no access link is drawn for X; FP=W.
(C) Only M,X,Y,Z are drawn: X→M, Y→M, Z→Y; W is absent and FP=X.
(D) X→M, Y→M, Z→Y, W→M; FP=W.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

An access link points to the activation of the lexically enclosing procedure, not generally to the caller. Both A1 activations and A2 are declared directly in Main, so all three point to Main. A21 is declared in A2, so its access link points to that A2 activation. The frame pointer is at the latest (bottom) A1 activation. Option D depicts precisely these static links; caller links instead would form the dynamic call chain.

Check: The second A1 was called by A21, but A1’s declaration remains inside main. Dynamic recursion changes which activation is current, not the lexical parent. Thus its static link skips both A21 and A2, while its dynamic caller link would point to A21.

Original paper, page 9 · Answer key

2 marks · MCQ
Report issue

FIRST and FOLLOW with nullable indirect productions

Parsing & Syntax Analysis

Question 52, GATE 2012: Grammar: S→aAbB | bAaB | ε; A→S; B→S. S is the start symbol. The partial predictive table has columns a,b,$: S row=[E1,E2,S→ε]; A row=[A→S,A→S,error]; B row=[B→S,B→S,E3]. ε is empty and $ is the input-end marker.
Find FIRST and FOLLOW of A and B.
(A) FIRST(A)=FIRST(B)={a,b,ε}; FOLLOW(A)={a,b}; FOLLOW(B)={a,b,$}.
(B) FIRST(A)={a,b,$}; FIRST(B)={a,b,ε}; FOLLOW(A)={a,b}; FOLLOW(B)={$}.
(C) FIRST(A)=FIRST(B)={a,b,ε}; FOLLOW(A)={a,b}; FOLLOW(B)=∅.
(D) FIRST(A)=FIRST(B)={a,b}; FOLLOW(A)=FOLLOW(B)={a,b}.
Question 52, GATE 2012: Grammar: S→aAbB | bAaB | ε; A→S; B→S. S is the start symbol. The partial predictive table has columns a,b,$: S row=[E1,E2,S→ε]; A row=[A→S,A→S,error]; B row=[B→S,B→S,E3]. ε is empty and $ is the input-end marker.
Find FIRST and FOLLOW of A and B.
(A) FIRST(A)=FIRST(B)={a,b,ε}; FOLLOW(A)={a,b}; FOLLOW(B)={a,b,$}.
(B) FIRST(A)={a,b,$}; FIRST(B)={a,b,ε}; FOLLOW(A)={a,b}; FOLLOW(B)={$}.
(C) FIRST(A)=FIRST(B)={a,b,ε}; FOLLOW(A)={a,b}; FOLLOW(B)=∅.
(D) FIRST(A)=FIRST(B)={a,b}; FOLLOW(A)=FOLLOW(B)={a,b}.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Step through it (14 steps)

S can start with a or b or derive ε; A→S and B→S therefore give FIRST(A)=FIRST(B)={a, b,ε}. In S→aAbB and S→bAaB, A is immediately followed by b and a respectively, so FOLLOW(A)={a, b}. Since S is the start symbol, $ belongs to FOLLOW(S). A→S passes FOLLOW(A) into FOLLOW(S), giving FOLLOW(S)={a, b,$}. B occurs at the end of each nonempty S production, so it inherits FOLLOW(S), and FOLLOW(B)={a, b,$}. B→S adds no new symbols. These are option A.

Check: Nullable propagation is essential: A and B derive ε through S even though neither has an explicit ε production. FOLLOW sets require a fixed point because A→S and B→S propagate symbols back to S, which then propagates them to trailing B.

Original paper, page 15 · Answer key

2 marks · MCQ
Report issue

Predictive-table conflicts in a non-LL(1) grammar

Parsing & Syntax Analysis

Question 53, GATE 2012: Grammar: S→aAbB | bAaB | ε; A→S; B→S. S is the start symbol. The partial predictive table has columns a,b,$: S row=[E1,E2,S→ε]; A row=[A→S,A→S,error]; B row=[B→S,B→S,E3]. ε is empty and $ is the input-end marker.
Fill E1,E2,E3.
(A) E1={S→aAbB,A→S}; E2={S→bAaB,B→S}; E3={B→S}.
(B) E1={S→aAbB,S→ε}; E2={S→bAaB,S→ε}; E3={S→ε}.
(C) E1={S→aAbB,S→ε}; E2={S→bAaB,S→ε}; E3={B→S}.
(D) E1={A→S,S→ε}; E2={B→S,S→ε}; E3={B→S}.
Question 53, GATE 2012: Grammar: S→aAbB | bAaB | ε; A→S; B→S. S is the start symbol. The partial predictive table has columns a,b,$: S row=[E1,E2,S→ε]; A row=[A→S,A→S,error]; B row=[B→S,B→S,E3]. ε is empty and $ is the input-end marker.
Fill E1,E2,E3.
(A) E1={S→aAbB,A→S}; E2={S→bAaB,B→S}; E3={B→S}.
(B) E1={S→aAbB,S→ε}; E2={S→bAaB,S→ε}; E3={S→ε}.
(C) E1={S→aAbB,S→ε}; E2={S→bAaB,S→ε}; E3={B→S}.
(D) E1={A→S,S→ε}; E2={B→S,S→ε}; E3={B→S}.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

For M[S, a], FIRST(aAbB) supplies S→aAbB; because a belongs to FOLLOW(S), the nullable alternative also supplies S→ε. Similarly M[S, b] contains both S→bAaB and S→ε. At M[B,$], B→S is inserted because S is nullable and $ belongs to FOLLOW(B). Thus E1={S→aAbB, S→ε}, E2={S→bAaB, S→ε}, E3={B→S}, exactly C. The two multiple-production cells are FIRST/FOLLOW conflicts, proving this grammar is not LL(1). The source’s phrase “LL(1) parsing table” should be understood as the table-construction procedure, not as certification that the grammar admits deterministic LL(1) parsing.

Check: Each parsing-table row can contain only productions whose left-hand side is that row’s nonterminal. This immediately eliminates options inserting A→S or B→S into S’s row, and eliminates S→ε as the B-row entry E3.

Original paper, page 15 · Answer key

1 mark · MCQ
Report issue

Compiler keyword recognition

Lexical Analysis

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

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

Official answer: C

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

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

Original paper, page 2 · Answer key

1 mark · MCQ
Report issue

Automaton model for lexical analysis

Lexical Analysis

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

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

Official answer: A

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

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

Original paper, page 5 · Answer key

2 marks · MCQ
Report issue

Precedence and associativity parse tree

Parsing & Syntax Analysis

Question 27, GATE 2011: For binary operators ↑ and ↓, ↑ has higher precedence and is right-associative, whereas ↓ is left-associative. Which parse tree represents 7↓3↑4↑3↓2? Trees are encoded below as fully parenthesized expressions.

(A) 7↓(3↑(4↑(3↓2)))
(B) (7↓(3↑(4↑3)))↓2
(C) 7↓(((3↑4)↑3)↓2)
(D) (((7↓3)↑4)↑3)↓2
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Higher-precedence ↑ groups the middle chain, and its right associativity gives 3↑(4↑3). Lower-precedence ↓ then associates left, yielding(7↓(3↑(4↑3)))↓2. The displayed tree with that structure is B.

Associativity is applied only after precedence identifies which operators compete at the same level. First make the ↑ subtree with root ↑, left leaf 3 and right subtree (4↑3). The remaining expression has the form 7↓T↓2; left associativity makes its root the final ↓, with right child 2 and left child (7↓T). A gives ↓2 too high a binding priority; C and D left-group the ↑ chain or combine the initial ↓ too early.

Original paper, page 7 · Answer key

2 marks · MCQ
Not in GATE 2027 syllabusReport issue

Registers for fixed expression-tree evaluation

Code Generation & Register Allocation

Question 36, GATE 2011: Evaluate the fixed expression tree (a-b)+(e-(c+d)) on a load-store machine. Leaves a,b,c,d,e start in memory. Binary operations require both operands in registers and leave their result in a register; no intermediate result may be stored in memory. What is the minimum number of registers needed? The tree must be evaluated as given.

(A) 2
(B) 9
(C) 5
(D) 3
Tap to enlarge
Your answer
Answer & solution

Official answer: D

A leaf needs 1 register; a binary node with equally demanding children needs one more than either, otherwise it needs the larger requirement when evaluated in the favorable order. Thus a−b needs 2; c+d needs 2; e−(c+d) also needs 2; the root combining two 2-register subtrees needs 3. Three suffice by retaining one subtree result while evaluating the other in two registers. Two cannot hold one completed child while evaluating the other fixed subtree. Hence D. This evaluates the supplied tree without algebraic reassociation; rewriting the arithmetic expression into a different tree changes the problem.

A concrete three-register schedule is: load c and d into R1,R2; replace R1 by c+d; load e into R2 and replace R2 by e-R1; then load a into R1 and b into R3, replace R1 by a-b, and add R1 to R2. The two main subtrees each need two registers to combine two operands. Whichever subtree finishes first leaves one live result while the second is evaluated, forcing a third register without spilling or reassociation.

Original paper, page 10 · Answer key

1 mark · MCQ
Report issue

Compiler variable attributes

Semantic Analysis & Type Checking

Question 13, GATE 2010: Which compiler data structure manages information about variables and their attributes?
Options: (A) Abstract syntax tree; (B) Symbol table; (C) Semantic stack; (D) Parse table.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

A symbol table stores identifier entries and attributes such as type, scope, storage location and parameter information. An abstract syntax tree represents program structure, a parse table guides parsing, and a semantic stack supports intermediate parser actions. Therefore the data structure asked for is the symbol table, B.

For example, a declaration “int count” can create a symbol-table entry recording the name count, integer type and scope. Later uses look up that entry for type checking and storage access. The syntax tree may refer to the entry but is not itself the lookup structure; a parse table instead maps parser states/lookahead to parsing actions.

Original paper, page 3

1 mark · MCQ
Report issue

Runtime heap allocation

Runtime Environments & Parameter Passing

Question 14, GATE 2010: Which class of programming languages necessarily needs heap allocation in its runtime environment?
Options: (A) Languages supporting recursion; (B) Languages using dynamic scoping; (C) Languages allowing dynamic data structures; (D) Languages using global variables.
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Dynamically created data structures can have sizes and lifetimes unrelated to the last-in-first-out nesting of procedure activations, so their runtime storage requires heap-style allocation in the standard implementation model. Recursion and dynamic scope can be supported with activation stacks; global variables can use static storage. C is the intended distinction. A language implementation may realize the allocator through a preallocated arena, but that is still heap-style management rather than a counterexample to the storage-lifetime distinction.

A recursive call creates a new activation record that can be popped when the call returns, so recursion alone needs a stack, not a heap. A linked node returned to a caller may have to survive its creator’s return and be freed in an arbitrary order. That non-LIFO lifetime is the key distinction tested by dynamic data structures.

Original paper, page 3

2 marks · MCQ
Not in GATE 2027 syllabusReport issue

Minimum registers without spilling

Code Generation & Register Allocation

Question 37, GATE 2010: All operations take operands from registers. What is the minimum number of registers needed to execute this program without spilling?
a=1; b=10; c=20;
d=a+b; e=c+d; f=c+e;
b=c+e; e=b+f; d=5+e;
return d+f;
Options: (A) 2; (B) 3; (C) 4; (D) 6.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Immediately after c=20, a,b,c are all live because a and b are needed for d=a+b while c is needed later. At least three registers are therefore necessary. Three suffice: put a,b,c in registers r1,r2,r3; overwrite r1 with d=a+b, then with e=c+d; overwrite r2 with f=c+e; overwrite r3 with b=c+e after c dies; overwrite r1 with e=b+f and then d=5+e. The final d+f uses r1 and r2. Thus 3, B, under the usual model allowing a destination to reuse a dead operand register.

One possible register state trace is (a,b,c)→(d,b,c)→(e,b,c)→(e,f,c)→(e,f,b)→(e,f,b)→(d,f,b), where dead values may be overwritten. At the middle expression f=c+e, both c and e must remain available for the following b=c+e, so the third register is still useful. The lower-bound argument assumes executing the given operations, rather than constant-folding the entire straight-line program.

Original paper, page 9

2 marks · MCQ
Report issue

Predictive and LR parsing of a grammar

Parsing & Syntax Analysis

Question 38, GATE 2010: Classify the grammar S→aSa | bS | c.
Options: (A) LL(1) but not LR(1); (B) LR(1) but not LL(1); (C) Both LL(1) and LR(1); (D) Neither LL(1) nor LR(1).
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Step through it (3 parts)

The productions S→aSa, S→bS and S→c begin with distinct terminals a,b,c and none derives epsilon. Their FIRST sets are disjoint, so one lookahead symbol uniquely selects the production and the grammar is LL(1). Every LL(1) grammar is LR(1), so it is both, C. The trailing a in aSa does not cause a predictive conflict because the initial a already selects that alternative.

The predictive parsing table contains exactly S→aSa under lookahead a, S→bS under b and S→c under c. There are no epsilon productions, so no FIRST/FOLLOW conflict arises. Recursion does not by itself prevent LL(1); left recursion would, but here each recursive call is preceded by a terminal consumed from the input.

Original paper, page 9

1 mark · MCQ
Report issue

Compiler activity matching

Compiler Phases, Linking & Loading

Question 17, GATE 2009: Match P regular expressions, Q pushdown automata, R dataflow analysis, S register allocation to 1 syntax analysis, 2 code generation, 3 lexical analysis, 4 code optimization. A P4Q1R2S3; B P3Q1R4S2; C P3Q4R1S2; D P2Q1R4S3.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Regular expressions specify tokens for lexical analysis(P→3). Pushdown automata model syntax analysis(Q→1). Dataflow facts support code optimization(R→4), while register allocation is part of code generation(S→2). Hence B.

Regular expressions specify lexical tokens, giving P3. A pushdown store models nested grammatical structure in syntax analysis, giving Q1. Dataflow facts support optimizations such as dead-code elimination and constant propagation, giving R4. Register allocation assigns machine storage during code generation, giving S2. All four pairings are needed: option B is the unique complete match.

Original paper, page 3

2 marks · MCQ
Report issue

Compiler implementation statements

Other / Mixed Topics

Question 42, GATE 2009: Assess I some programming-language parsers have complexity below Θ(n³); II recursion can be implemented with static storage allocation; III no L-attributed definition can be evaluated bottom-up; IV optimization can occur at source and intermediate-code levels. A I/II; B I/IV; C III/IV; D I/III/IV.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

I is true: LL/LR parsing for suitable grammars runs in linear time, below the general cubic CFL bound. II is false for unrestricted recursion under static allocation of activation records, since simultaneous recursive calls need distinct storage. III is false because S-attributed definitions are also L-attributed and can be evaluated bottom-up. IV is true: optimizations may occur at source and intermediate-code levels. Thus I and IV, B. Tail-recursive/bounded special cases do not justify the unrestricted static-allocation claim.

LL/LR parsers for suitable grammars run in linear time, establishing I without claiming every CFG can be parsed that way. Unbounded recursive activation records cannot all be assigned one fixed static location, so II is false in the intended general model. S-attributed definitions are a subclass of L-attributed ones and can be evaluated bottom-up, disproving III’s universal negative. Algebraic source rewrites and intermediate-code optimizations illustrate IV. Therefore I and IV are true.

Original paper, page 9

1 mark · MCQ
Report issue

Handle in LR parsing

Parsing & Syntax Analysis

Question 11, GATE 2008: Which describes a handle in LR parsing?

(A) A position in a sentential form for the next shift or reduce operation
(B) A nonterminal whose production is used for the next reduction
(C) A production possibly used for a future reduction and the position of the next shift or reduce operation
(D) The production used in the next reduction and the position of its right-hand side in the sentential form
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. Bottom-up LR parsing reverses a rightmost derivation: it replaces a production’s right-hand side by its left-hand-side nonterminal.
2. A handle must specify both which production to reduce and which occurrence of its right-hand side is the correct next one. Merely naming a position or a nonterminal is insufficient.
3. D gives exactly this production-and-position pair. A possible future reduction, as in C, is not necessarily the next handle.

Original paper, page 3

1 mark · MCQ
Report issue

Intermediate-code optimization portability

Code Optimization & Data-Flow Analysis

Question 12, GATE 2008: Why are some code optimizations performed on intermediate code?

(A) They enhance compiler portability to other target processors
(B) Program analysis is more accurate on intermediate code than machine code
(C) Dataflow-analysis information cannot otherwise be used for optimization
(D) Front-end information cannot otherwise be used for optimization
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. Intermediate code abstracts away many machine-specific details, allowing one optimization pass to serve several target back ends.
2. This reuse makes it easier to retarget the compiler, which is the portability benefit in A.
3. B claims a universal analysis-accuracy advantage that does not follow. C and D incorrectly say dataflow/front-end information cannot otherwise be used; such information can also inform other compilation stages.

Original paper, page 3

2 marks · MCQ
Report issue

Activation records, recursion and escaping closures

Runtime Environments & Parameter Passing

Question 54, GATE 2008: Which are true? I: a language without globals or nested procedures, but with recursion, can use static storage allocation. II: multilevel access links/displays are needed only for languages with nested procedures. III: recursion cannot use dynamic storage allocation. IV: nesting and recursion require heap allocation and cannot use stack activation records. V: languages allowing a function to return a function cannot use only stack allocation for activation records.

(A) II and V only
(B) I,III,IV only
(C) I,II,V only
(D) II,III,V only
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. Under the standard language-runtime assumptions, II and V are true, giving A. I is false: recursive calls can have arbitrarily many simultaneously live instances of local variables, so one statically allocated activation record per procedure is insufficient even without globals or nested procedures.
2. II is true: multilevel static access links/displays serve access to lexically enclosing procedures; without lexical nesting no multilevel environment chain is needed. III is false because dynamic stack allocation supports ordinary recursion.
3. IV is false because nested procedures and recursion alone can use stack activation records with static/dynamic links. V describes a returned nested function that can retain its defining environment after the creator returns: pure stack allocation cannot preserve that environment, so escaping environments need extended lifetime, normally heap allocation or copying.
4. The literal statement V is too broad without that escaping-closure assumption: a function may return a pointer to a global function, or a function with no captured environment, while ordinary activation records remain stack allocated. Thus A is the intended answer under the nested escaping-function interpretation, not a universal consequence of merely returning any function.

Original paper, page 11

2 marks · MCQ
Report issue

Shift-reduce conflicts under LALR merging

Parsing & Syntax Analysis

Question 55, GATE 2008: An LALR(1) parser for G has shift-reduce conflicts if and only if:

(A) Its SLR(1) parser has shift-reduce conflicts
(B) Its LR(1) parser has shift-reduce conflicts
(C) Its LR(0) parser has shift-reduce conflicts
(D) Its LALR(1) parser has reduce-reduce conflicts
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. The equivalence is with canonical LR(1), option B. An LALR state merges LR(1) states having the same LR(0) core and unions lookaheads. Suppose a merged state has a reduction A→α on lookahead a and a shift on a.
2. The reduction/lookahead pair came from some original LR(1) state. The shift item is in the shared LR(0) core, so it also occurred in that very original state. Thus the shift-reduce conflict already existed before merging.
3. Conversely a conflict in an original LR(1) state survives the merge. Merging can introduce reduce-reduce conflicts, but cannot create a new shift-reduce conflict. SLR/LR(0) may report conflicts avoided by finer LR(1) lookaheads.

Original paper, page 11

1 mark · MCQ
Report issue

Top-down parsing method

Parsing & Syntax Analysis

Question 18, GATE 2007: Which is a top-down parser?
Options:
(A) Recursive descent
(B) Operator precedence
(C) LR(k)
(D) LALR(k)
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. Approach. Top-down parsing constructs a derivation beginning with the start symbol. Bottom-up parsing starts with input symbols and reduces them toward the start symbol.

2. Derivation and interpretation. Recursive descent starts from the grammar’s start symbol and expands productions while matching input, so it is top-down. Operator-precedence, LR and LALR parsers reduce handles bottom-up. Therefore A.

Original paper, page 4

2 marks · MCQ
Report issue

Dangling-else grammar is not LL(1)

Parsing & Syntax Analysis

Question 52, GATE 2007: A grammar has nonterminals S,C,S1, terminals a,b,i,t,e, start S, and productions S→iCtSS1 | a; S1→eS | ε; C→b. Why is this grammar not LL(1)?
Options:
(A) It is left recursive
(B) It is right recursive
(C) It is ambiguous
(D) It is not context-free
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. Approach. Read i,t,e as if, then, else. In nested conditionals, an else can attach to either the inner or the outer if. Exhibit two parses of the same string to prove ambiguity.

2. Derivation and interpretation. The grammar is S→iCtSS₁ | a, S₁→eS | ε, C→b. It is the dangling-else grammar. The string i b t i b t a e a has two parse trees: the e a can belong to the inner conditional (inner S₁→eS, outer S₁→ε) or the outer conditional (inner S₁→ε, outer S₁→eS). Therefore it is ambiguous and cannot be LL(1), giving C. Equivalently e belongs both to FIRST(eS) and FOLLOW(S₁), causing a prediction-table conflict with S₁→ε. Right recursion by itself is not an obstruction to LL(1), and these productions are context-free and not left recursive.

Original paper, page 12

2 marks · MCQ
Report issue

Regular grammars versus existence of LR(1) grammars

Parsing & Syntax Analysis

Question 53, GATE 2007: Consider P: Every regular grammar is LL(1). Q: Every regular language has an LR(1) grammar. Which is true?
Options:
(A) Both P and Q true
(B) P true,Q false
(C) P false,Q true
(D) Both false
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. Approach. P concerns every presentation of a language, whereas Q asks whether a suitable presentation exists. A language can have a poorly factored grammar even though another grammar parses deterministically.

2. Derivation and interpretation. P is false: the right-linear regular grammar S→aA | aB, A→b, B→c has two alternatives whose FIRST sets both contain a, so this particular grammar is not LL(1). Q is true: construct a grammar from a DFA by using one nonterminal per state, production Q→aR for each transition on a, and Q→ε for each accepting state. Determinism gives at most one alternative per terminal; epsilon is selected at end of input. This yields an LL(1), hence LR(1), grammar for the regular language (or use the standard inclusion of regular languages in deterministic context-free languages). Thus P false and Q true, option C.

Original paper, page 13

2 marks · MCQ
Not in GATE 2027 syllabusReport issue

Register allocation and MOV count in a basic block

Code Generation & Register Allocation

Question 54, GATE 2007: A computer has only two registers. Instructions OP Rj,Ri store Rj OP Ri in Ri; OP m,Ri store M[m] OP Ri in Ri; OP is ADD or SUB. MOV m,Ri loads memory into a register and MOV Ri,m stores a register to memory. Generate code for t1=a+b; t2=c+d; t3=e−t2; t4=t1−t3. All operands start in memory and the final result must be in memory. What minimum MOV count is intended?
Options:
(A) 2
(B) 3
(C) 5
(D) 6
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Approach. Track the unusual operand order: SUB e,R2 computes e−R2, not R2−e. Under expression-preserving generation, retain t1 in one register while computing t2 and t3 in the other. The scope of permitted algebraic rewrites affects the literal minimum.

2. Derivation and interpretation. For expression-preserving code generation, three MOVs suffice: MOV a,R1; ADD b,R1; MOV c,R2; ADD d,R2; SUB e,R2; SUB R1,R2; MOV R2,t4. The specified source-minus-destination semantics gives R1=t1, R2=t2 then t3=e−t2 then t4=t1−t3. There are two loads to initialize the two independently computed subexpressions and one store, yielding the intended option B (3). This minimum presumes the usual task of generating code for the given expression structure. If algebraic reassociation is allowed, two MOVs suffice: MOV c,R1; ADD d,R1; SUB e,R1; SUB a,R1; ADD b,R1; MOV R1,t4. This computes t4=a−(e−(c+d))+b. Furthermore, if arbitrary arithmetic instructions may initialize a register, SUB R1,R1 makes zero; replacing the initial MOV c,R1 by SUB R1,R1; ADD c,R1 leaves only the final MOV. Hence the literal unrestricted minimum is not 3, and the scope assumption must be disclosed; B is an intended, conditional answer rather than an unconditional theorem.

Original paper, page 13

1 mark · MCQ
Report issue

Canonical LR zero item sets

Parsing & Syntax Analysis

Question 7, GATE 2006: Grammar: S→S*E | E; E→F+E | F; F→id. Consider LR(0) items 1: S→S*·E; 2: E→F·+E; 3: E→F+·E. Which pair appears together in a canonical item set?
Options:
(A) 1 and 2
(B) 2 and 3
(C) 1 and 3
(D) None of these pairs
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

Step through it (12 steps)

1. The state after recognizing S* contains S→S*·E plus closure items E→·F+E,E→·F,F→·id. The item E→F·+E occurs after a transition on F, together with E→F·.

2. The item E→F+·E occurs after a further transition on +, again with the initial E/F closure. These three kernels are different states; closure does not introduce either of the other listed advanced items.

3. Thus none of the listed pairs coexist, D.

4. Teaching check: LR closure inserts productions with the dot at their beginning when a nonterminal follows the dot. It never advances an existing dot. Thus an item beginning E→·F can coexist with item 1, but the advanced E→F·+E requires a GOTO on F, producing another state.

Original paper, page 1

2 marks · MCQ
Report issue

Common-subexpression reuse across an array store

Code Optimization & Data-Flow Analysis

Question 55, GATE 2006: Consider C functions:
int work 1(int *a,int i,int j) {
 int x=a[i+2]; a[j]=x+1; return a[i+2]-3;
}
int work 2(int *a,int i,int j) {
 int t1=i+2; int t2=a[t1]; a[j]=t2+1; return t2-3;
}
S1: work 2 always gives the same output and effect on state as work 1.
S2: the transformations always reduce CPU time.
Which truth values apply?
Options:
(A) S1 false, S2 false
(B) S1 false, S2 true
(C) S1 true, S2 false
(D) S1 true, S2 true
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. work 1 reads a[i+2], writes a[j], then reads a[i+2] again in its return expression. work 2 saves the first value and reuses it after the store. If j=i+2, the store changes the location that work 1 rereads, so the functions need not return the same value; S1 is false.

2. Compiler transformations also do not universally improve runtime on every target/input, and this transformation is not even semantics-preserving without a non-alias condition. S2 is false.

3. Thus A.

4. For i=0, j=2, initial a[2]=5, work 1 returns 3 whereas work 2 returns 2.

5. Teaching check: Take i=0,j=2,a[2]=5. Both functions store 6 into a[2], but work 1 then rereads 6 and returns 3, while work 2 reuses saved 5 and returns 2. Reusing a load across a potentially aliasing store is not a valid unconditional common-subexpression transformation.

Original paper, page 8

2 marks · MCQ
Report issue

Pass-by-reference with an expression argument

Runtime Environments & Parameter Passing

Question 56, GATE 2006: A pedagogical pass-by-reference language executes:
subroutine swap(ix,iy)
 it=ix
 L1: ix=iy
 L2: iy=it
end
ia=3; ib=8; call swap(ia,ib+5); print ia,ib.
Statements: S1 an unnamed temporary initialized to 13 is allocated and its address passed for the second argument; S2 runtime error at L1; S3 runtime error at L2; S4 prints 13,8; S5 prints 13,−2. Which stated set is correct under the expression-to-temporary model?
Options:
(A) S1 and S2
(B) S1 and S4
(C) S3
(D) S1 and S5
Question 56, GATE 2006: A pedagogical pass-by-reference language executes:
subroutine swap(ix,iy)
 it=ix
 L1: ix=iy
 L2: iy=it
end
ia=3; ib=8; call swap(ia,ib+5); print ia,ib.
Statements: S1 an unnamed temporary initialized to 13 is allocated and its address passed for the second argument; S2 runtime error at L1; S3 runtime error at L2; S4 prints 13,8; S5 prints 13,−2. Which stated set is correct under the expression-to-temporary model?
Options:
(A) S1 and S2
(B) S1 and S4
(C) S3
(D) S1 and S5
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Initially ia=3 and ib=8; the expression ib+5 evaluates to 13. Under the stated expression-to-temporary reference model, the compiler passes the address of a temporary containing 13, not the address of ib. swap sets ia to 13 and the temporary to 3; ib remains 8.

2. S1 and S4 hold, so B. This is the pedagogical model specified by the options, not a guarantee that every actual FORTRAN standard/compiler permits defining an expression-associated dummy argument.

3. Teaching check: The expression ib+5 has a value but is not the storage cell ib. Passing a temporary permits swap to overwrite the argument without overwriting ib. Trace the two addressed cells separately: ia changes 3→13, temporary changes 13→3, and ib stays 8.

Original paper, page 8

2 marks · MCQ
Report issue

Predictive parsing table with epsilon production

Parsing & Syntax Analysis

Question 58, GATE 2006: For grammar S→FR, R→*S|ε, F→id, what are predictive-table entries M[S,id] and M[R,$], respectively?
Options:
(A) {S→FR}, {R→ε}
(B) {S→FR}, empty
(C) {S→FR}, {R→*S}
(D) {F→id}, {R→ε}
Question 58, GATE 2006: For grammar S→FR, R→*S|ε, F→id, what are predictive-table entries M[S,id] and M[R,$], respectively?
Options:
(A) {S→FR}, {R→ε}
(B) {S→FR}, empty
(C) {S→FR}, {R→*S}
(D) {F→id}, {R→ε}
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step through it (2 parts)

1. For S→FR, R→*S|ε, F→id, FIRST(FR)={id}; hence M[S,id]={S→FR}. Since S is the start symbol and R occurs at the end of S→FR, $ belongs to FOLLOW(R).

2. Therefore M[R,$]={R→ε}. Option A.

3. Teaching check: An LL(1) table uses FIRST of a nonempty production; ε productions use FOLLOW of their left-hand side. Since id begins FR, the S/id cell receives S→FR. Since R can end the start-symbol derivation, end marker $ belongs to FOLLOW(R).

Original paper, page 8

2 marks · MCQ
Report issue

Translation scheme with nonstandard precedence

Semantic Analysis & Type Checking

Question 59, GATE 2006: A syntax-directed translation has productions:
S→ER
R→*E {print('*')} R | ε
E→F+E {print('+')} | F
F→(S) | id {print(id.value)}
Here id denotes an integer. What is printed on input 2*3+4?
Options:
(A) 2*3+4
(B) 2*+34
(C) 23*4+
(D) 234+*
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. S→ER and R→*E{print(*)}R|ε put multiplication below the expression E; E→F+E{print(+)}|F groups the addition on the right. For 2*3+4, first print 2, then parse E for 3+4, printing 3,4,+, then print * when that E finishes.

2. The output is 234+*, option D. Applying ordinary arithmetic precedence would incorrectly give 23*4+.

3. Teaching check: Semantic print actions fire at their positions in the grammar, not according to the usual arithmetic-precedence rules. The E nonterminal consumes the whole 3+4 before R’s multiplication-print action runs. The result is therefore postfix for 2*(3+4).

Original paper, page 9

2 marks · MCQ
Report issue

Identifying unavailable loop optimization

Code Optimization & Data-Flow Analysis

Question 60, GATE 2006: Consider C code (with defined arithmetic and x,y live after the fragment):
for (i=0;i<n;i++) {
 for (j=0;j<n;j++) {
  if (i%2) { x+=(4*j+5*i); y+=(7+4*j); }
 }
}
Which optimization claim is not supported by this fragment?
Options:
(A) It contains loop-invariant computation
(B) Common-subexpression elimination is possible
(C) Strength reduction is possible
(D) Dead-code elimination is possible
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. Within the inner j loop, i%2 and 5*i are invariant. The expression 4*j occurs in both updates and can be shared.

2. The products by loop indices can use strength reduction through induction-variable increments. However x and y are updated and may be used later; nothing in the snippet establishes that those results are dead.

3. Therefore the claim of available dead-code elimination is unsupported and is the intended false statement, D. This uses the ordinary compiler-question assumption that program behavior is defined and x,y remain live afterward.

4. Teaching check: An expression can be expensive and still necessary. Dead-code elimination requires showing that its computed value never affects observable behavior, which is not established for x or y. In contrast, the repeated arithmetic patterns are visible directly within the loops.

Original paper, page 9

1 mark · MCQ
Report issue

Predictive parsing and two grammar defects

Parsing & Syntax Analysis

Question 14, GATE 2005: Grammar A→AA|(A)|ε is unsuitable for predictive parsing because it is: A ambiguous; B left-recursive; C right-recursive; D an operator grammar. Assess the nonunique objections rather than forcing one choice.
Tap to enlarge
Your answer
Answer & solution

Answer: Both A and B are valid objections (no official key was published)

The production A→AA is directly left-recursive, so a naive predictive recursive-descent parser can recur indefinitely before consuming input; this is B. The same grammar is also ambiguous: ε has the distinct derivations A→ε and A→AA→εA→ε, giving different parse trees. An ambiguous grammar cannot be LL(1), so A is also a valid reason. Therefore the single-choice wording does not uniquely distinguish these two objections. Right recursion alone is not a barrier to predictive parsing.

The production A→AA begins with the same nonterminal, so direct predictive expansion can recurse without consuming input. Independently, ε has distinct parse trees A⇒ε and A⇒AA⇒εε, demonstrating ambiguity. A grammar with these properties cannot be LL(1), making both A and B valid reasons in the literal single-choice wording. Right recursion alone is not an objection to predictive parsing, and adjacent nonterminals also prevent the standard operator-grammar restriction.

Original paper, page 2

2 marks · MCQ
Report issue

Handles in an expression reduction

Parsing & Syntax Analysis

Question 59, GATE 2005: Grammar E→E+n | E×n | n generates n+n×n. List the handles in bottom-up reduction order. A n, E+n, E+n×n; B n, E+n, E+E×n; C n, n+n, n+n×n; D n, E+n, E×n.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

Step through it (10 steps)

The rightmost derivation is E ⇒ E×n ⇒ E+n×n ⇒ n+n×n. Reversing it reduces the leftmost n first, then E+n, then E×n. These handles are n, E+n, E×n, option D. The fixed terminal n on the right of each operator means this is not the usual ambiguous E→E+E|E×E grammar.

A handle is the RHS whose reduction undoes one step of a rightmost derivation, not an arbitrary matching substring. Reverse the displayed derivation: n+n×n→E+n×n→E×n→E. The successive reduced RHS strings are n, E+n and E×n. Reducing the rightmost terminal n first would not reverse this rightmost derivation. The grammar’s fixed terminal right operands force the association, unlike E→E+E.

Original paper, page 7

2 marks · MCQ
Report issue

SLR canonical LR and LALR state counts

Parsing & Syntax Analysis

Question 60, GATE 2005: For S→(S)|a, let n1, n2, n3 count SLR(1), canonical LR(1), LALR(1) states. In GFG: A n1<n2<n3; B n1=n3<n2; C n1=n2=n3; D n1=n3=n2 (duplicated equality as reproduced). Determine the actual counts independently; alternate distractor ordering differs.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

For augmented S′→S and S→(S)|a, LR(0) has six states with kernels S′→·S, S′→S·, S→(·S), S→a·, S→(S·), and S→(S)· (including closures). Canonical LR(1) separates the inner/non-inner versions with lookaheads ) and $, yielding ten states. Merging identical LR(0) cores gives six LALR states again. Therefore n1=n3<n2, B.

SLR states are LR(0) item-set states, so its FOLLOW-based action construction does not add states. The six cores are listed in the baseline derivation. Canonical LR(1) retains context: an expression enclosed by parentheses must expect a closing parenthesis, whereas the outer expression expects end-of-input, creating extra versions of cores and ten states. LALR merges versions sharing the same LR(0) core, restoring six. Therefore 6=6<10 in the order n1, n3, n2.

Original paper, page 7

2 marks · MCQ
Report issue

Yacc default ambiguity resolution

Parsing & Syntax Analysis

Question 83a, GATE 2005: Expression grammar E→number | E+E | E×E has the usual synthesized arithmetic values and is given to yacc without precedence/associativity declarations. Printed 83(a): yacc A detects/eliminates recursion; B resolves reduce/reduce conflict; C resolves shift/reduce in favor of shift; D resolves shift/reduce in favor of reduce.
Question 83a, GATE 2005: Expression grammar E→number | E+E | E×E has the usual synthesized arithmetic values and is given to yacc without precedence/associativity declarations. Printed 83(a): yacc A detects/eliminates recursion; B resolves reduce/reduce conflict; C resolves shift/reduce in favor of shift; D resolves shift/reduce in favor of reduce.
Question 83a, GATE 2005: Expression grammar E→number | E+E | E×E has the usual synthesized arithmetic values and is given to yacc without precedence/associativity declarations. Printed 83(a): yacc A detects/eliminates recursion; B resolves reduce/reduce conflict; C resolves shift/reduce in favor of shift; D resolves shift/reduce in favor of reduce.
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

The grammar E→number | E+E | E×E is ambiguous. After recognizing E+E or E×E, a following operator permits either reduction of the completed expression or shifting to build the right operand further. This is a shift/reduce conflict. With no precedence/associativity declarations, yacc defaults to shifting, option C; left recursion itself is valid for LR parsing.

After E+E has been recognized and a further operator is seen, the parser can either reduce the completed expression now or shift the operator to extend its right operand. The grammar does not specify which grouping is intended, hence a shift/reduce conflict. yacc’s default selects shift. Left recursion is supported naturally by LR parsing and is not removed automatically; no two distinct completed production reductions cause this particular ambiguity.

Original paper, page 12

2 marks · MCQ
Report issue

Expression evaluation with default shifts

Parsing & Syntax Analysis

Question 83b, GATE 2005: Expression grammar E→number | E+E | E×E has the usual synthesized arithmetic values and is given to yacc without precedence/associativity declarations. Printed 83(b): under its default resolution, how is 3×2+1 interpreted? A equal precedence, left associative, result 7; B equal precedence, right associative, result 9; C ×higher, left associative, result 7; D +higher, left associative, result 9.
Question 83b, GATE 2005: Expression grammar E→number | E+E | E×E has the usual synthesized arithmetic values and is given to yacc without precedence/associativity declarations. Printed 83(b): under its default resolution, how is 3×2+1 interpreted? A equal precedence, left associative, result 7; B equal precedence, right associative, result 9; C ×higher, left associative, result 7; D +higher, left associative, result 9.
Question 83b, GATE 2005: Expression grammar E→number | E+E | E×E has the usual synthesized arithmetic values and is given to yacc without precedence/associativity declarations. Printed 83(b): under its default resolution, how is 3×2+1 interpreted? A equal precedence, left associative, result 7; B equal precedence, right associative, result 9; C ×higher, left associative, result 7; D +higher, left associative, result 9.
Question 83b, GATE 2005: Expression grammar E→number | E+E | E×E has the usual synthesized arithmetic values and is given to yacc without precedence/associativity declarations. Printed 83(b): under its default resolution, how is 3×2+1 interpreted? A equal precedence, left associative, result 7; B equal precedence, right associative, result 9; C ×higher, left associative, result 7; D +higher, left associative, result 9.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Using the default shift resolution from part(a), neither operator receives a special precedence declaration and pending operators are reduced from the right. Thus 3×2+1 is parsed as 3×(2+1)=9. This behaves as equal precedence and right associativity, option B. This conclusion is conditional on the default shift resolution, not on adding conventional arithmetic precedence declarations.

At the + following 3×2, shifting postpones reducing 3×2. The parser first combines 2+1, then multiplies that result by 3, giving 9. Applying the same shift default to repeated operators creates right association. This is not evidence of a declared higher precedence for+: the behavior is the equal-precedence default arising from unresolved conflicts. A user-supplied precedence declaration could intentionally change the result.

Original paper, page 12

1 mark · MCQ
Report issue

Forbidden operator-grammar productions

Parsing & Syntax Analysis

Question 8, GATE 2004: P,Q,R are nonterminals and r,s,t are terminals. Which rules violate the requirements for an operator grammar? (i) P→QR; (ii) P→QsR; (iii) P→ε; (iv) P→QtRr.
Options:
(A) i only
(B) i and iii only
(C) ii and iii only
(D) iii and iv only
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. An operator grammar forbids adjacent nonterminals on a right-hand side and, in the standard definition used here, empty productions. P→QR violates the first rule and P→ε the second.

2. P→QsR and P→QtRr separate nonterminals by terminals. Thus i and iii, B.

3. Teaching check: A right-hand side can contain several nonterminals provided terminals separate adjacent ones. Thus QsR and QtRr are permitted. The empty-production restriction belongs to the conventional operator-grammar definition used here; do not confuse this syntactic test with conflict-free operator-precedence parsing.

Original paper, page 1

1 mark · MCQ
Not in GATE 2027 syllabusReport issue

Resolving an external function reference

Compiler Phases, Linking & Loading

Question 9, GATE 2004: A program has separately stored source modules M1 and M2. M1 refers to a function defined in M2. At what stage is this reference resolved in the conventional separate-compilation model?
Options:
(A) Edit time
(B) Compile time
(C) Link time
(D) Load time
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. With conventional separate compilation and static linking, each module produces an object file with symbol definitions/references. The linker matches the external reference in M1 to the definition in M2, so link time, C.

2. Dynamic loading can defer binding, but is not the default compilation model stated here.

3. Teaching check: Compilation can emit an unresolved external symbol into M1’s object file. Linking has access to both objects and supplies the address from M2. Editing only changes text; loading places an already linked image into memory under the assumed static-binding model.

Original paper, page 2

1 mark · MCQ
Not in GATE 2027 syllabusReport issue

Evaluation order with one accumulator

Code Generation & Register Allocation

Question 10, GATE 2004: For E→E1−E2, generate code for a CPU with only one user register. Subtraction requires its first operand in that register; E1 and E2 have no common subexpression. Which evaluation order gives the shortest code?
Options:
(A) Evaluate E1 first
(B) Evaluate E2 first
(C) Necessarily interleave E1 and E2 evaluation
(D) Evaluation order is of no consequence
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Evaluate E2 first and save its value in a temporary memory location. Then evaluate E1, leaving the required first operand in the sole register, and subtract the saved E2.

2. Evaluating E1 first would require saving it, evaluating/storing E2, then reloading E1 before subtraction. Thus E2-first, B, avoids an extra reload in the stated accumulator-style model, assuming both expressions require evaluation and their order is free of side-effect constraints.

3. Teaching check: The final subtraction needs register=E1 and memory temporary=E2. E2-first naturally reaches that arrangement after one save. E1-first must preserve E1 across E2’s evaluation, then reload it, adding a memory operation. This argument assumes unrestricted evaluation order and nontrivial expression evaluations.

Original paper, page 2

2 marks · MCQ
Report issue

Translation-rule precedence

Semantic Analysis & Type Checking

Question 45, GATE 2004: Grammar and semantic rules, start E: E→E1 # T with E.value=E1.value×T.value, or E→T with E.value=T.value; T→T1 & F with T.value=T1.value+F.value, or T→F with T.value=F.value; F→num with F.value=num.value. Find the root value for 2 # 3 & 5 # 6 & 4. The addition rule is visible in GFG; GateForum instead prints multiplication for that rule as well.
Options:
(A) 200
(B) 180
(C) 160
(D) 40
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. The grammar groups & inside T, hence it has higher precedence than #. Image the T→T1 & F semantic rule is T.value=T1.value+F.value, while E→E1 # T multiplies.

2. Therefore 2 # 3 & 5 # 6 & 4 evaluates as 2×(3+5)×(6+4)=160, option C.

4. Teaching check: Precedence comes from the grammar, not the symbols’ usual meanings. T binds & before the E-level #. Thus the parse groups 3&5 and 6&4 before combining the factors with #.

Original paper, page 6

1 mark · MCQ
Report issue

Limits of LL-one grammar transformations

Parsing & Syntax Analysis

Question 16, GATE 2003: Which transformation suffices to turn an arbitrary context-free grammar into an LL(1) grammar? A. Removing left recursion alone; B. Left factoring alone; C. Both removing left recursion and left factoring; D. None of these.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. LL(1) requires a deterministic choice of production from one lookahead symbol. Factoring resolves shared prefixes and removing left recursion removes an immediate predictive-parsing obstacle; neither establishes the required disjoint prediction sets in all grammars. In particular LL(1) cannot describe every context-free language.

2. Removing left recursion and left factoring remove common obstacles but do not make every CFG LL(1). Inherently ambiguous CFLs have no unambiguous grammar, whereas every LL(1) grammar is unambiguous; some unambiguous CFLs also are not LL(1). Thus none of the proposed transformations suffices for an arbitrary CFG, D.

Original paper, page 2

1 mark · MCQ
Report issue

SLR and LALR state counts

Parsing & Syntax Analysis

Question 17, GATE 2003: The SLR parser for grammar G has n₁ states and its LALR parser has n₂ states. Which relationship is necessary in the standard constructions? A. n₁<n₂; B. n₁=n₂; C. n₁>n₂; D. None of these.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. SLR states are sets of LR(0) items. Start with canonical LR(1) states for LALR and discard lookaheads to identify equal cores; merging those states leaves the reachable LR(0) cores. Different reduction entries in the tables do not create extra automaton cores.

2. SLR uses the canonical LR(0) item-state cores. LALR merges canonical LR(1) states that share an LR(0) core, leaving one state per such core. Thus their automata have the same number of states, n 1=n 2, B, under the conventional constructions, even though their reduction lookaheads and conflict behavior differ.

Original paper, page 2

1 mark · MCQ
Report issue

Inherited attributes during bottom-up parsing

Semantic Analysis & Type Checking

Question 18, GATE 2003: In bottom-up evaluation of a syntax-directed definition, inherited attributes can: A. Always be evaluated; B. Be evaluated only if the definition is L-attributed; C. Be evaluated only if the definition has synthesized attributes; D. Never be evaluated. Discuss the usual parsing-time interpretation and its limitation.
Tap to enlarge
Your answer
Answer & solution

Answer: B under a restricted one-pass evaluation model (no official key was published)

1. A synthesized attribute flows from children to parent and is naturally evaluated when a bottom-up parser reduces a production. An inherited attribute flows from parent or siblings toward a child and may be needed before that child is reduced. Therefore identify which dependency schedule the question permits before selecting an option.

2. Inherited attributes cannot in general be computed by the simple reduce-only mechanism used for synthesized attributes. In the usual left-to-right one-pass implementation, usable inherited information must be available from the parent context and already processed left siblings, the L-attributed dependency condition behind B. Even then suitable scheduling/marker productions or stack access may be needed; being L-attributed is not a blanket guarantee for every unmodified LR evaluation scheme. If bottom-up evaluation instead allows building a full parse/dependency graph and later scheduling arbitrary acyclic dependencies, L-attributedness is not necessary. The choice therefore depends on the conventional parsing-time model, which the prompt does not spell out.

Original paper, page 2

2 marks · MCQ
Report issue

Predictive-table conflict for a dangling-else grammar

Parsing & Syntax Analysis

Question 56, GATE 2003: For the grammar S→iEtSS′ | a; S′→eS | ε; E→b, consider the usual predictive parsing table M with end marker $. What are M[S′,e] and M[S′,$], respectively?
A. {S′→eS}, {S′→ε}
B. {S′→eS}, ∅
C. {S′→ε}, {S′→ε}
D. {S′→eS,S′→ε}, {S′→ε}
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

Step through it (2 parts)

1. FIRST(eS)={e}, so insert S′→eS in the e column.
2. S is the start symbol, so $∈FOLLOW(S). In S→iEtSS′, the first S is followed by nullable S′ whose nonempty FIRST is {e}; hence e∈FOLLOW(S) as well.
3. The final S′ inherits FOLLOW(S), giving FOLLOW(S′)={e,$}. For the ε production, put S′→ε in every FOLLOW column, therefore both e and $.
4. The resulting cells are {eS,ε} and {ε}, option D. The two entries in the e cell are the dangling-else conflict, so the grammar itself is not LL(1).

Solution: FIRST(eS)={e}, so the rule S′→eS enters M[S′,e]. Because S′ can be empty and follows S in S→iEtSS′, e belongs to FOLLOW(S), while $ belongs to FOLLOW(S) because S is the start symbol. The trailing S′ inherits FOLLOW(S), giving FOLLOW(S′)={e,$}. Thus S′→ε also enters both cells. The e cell contains both alternatives and the $ cell contains only ε, option D; the conflict means this grammar is not LL(1).

Original paper, page 8

2 marks · MCQ
Report issue

LL(1) classification from disjoint FIRST sets

Parsing & Syntax Analysis

Question 57, GATE 2003: Consider S→CC and C→cC | d. This grammar is:
A. LL(1)
B. SLR(1) but not LL(1)
C. LALR(1) but not SLR(1)
D. LR(1) but not LALR(1)
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step through it (2 parts)

1. C generates zero or more c symbols followed by d. Its alternatives begin with distinct terminal symbols: FIRST(cC)={c} and FIRST(d)={d}.
2. Neither C alternative is nullable, so no FIRST/FOLLOW overlap can create a second entry in its parsing-table cells. Put C→cC under c and C→d under d.
3. S has only one production; under either c or d use S→CC. No table cell has two choices. Thus one lookahead symbol always selects a production and the grammar is LL(1), A.

Solution: For C→cC|d the alternatives have disjoint FIRST sets {c} and {d}, and neither can derive ε. S has only its single production S→CC. Therefore every predictive-table cell has at most one production and the grammar is LL(1), option A. No stronger bottom-up distinction is needed.

Original paper, page 8

2 marks · MCQ
Report issue

Output order of embedded translation actions

Semantic Analysis & Type Checking

Question 58, GATE 2003: A translation scheme is S→TR; R→+ T {print('+');} R | ε; T→num {print(num.val);}. Token num represents an integer, and num.val is its value. For input 9+5+2, what is printed?
A. 9+5+2
B. 95+2+
C. 952++
D. ++952
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Step through it (19 steps)

1. Expand S→TR. The initial T consumes 9 and immediately prints 9.
2. The first R consumes + and invokes T on 5, printing 5. Its following action prints + before the recursive R begins.
3. That recursive R consumes +, invokes T on 2 and prints 2, then prints +. Its final R chooses ε and prints nothing.
4. Concatenating the actions yields 9,5,+,2,+, or 95+2+, B. Moving the plus action to after the recursive R would change the result, but that is not this scheme.

Solution: The initial T prints 9. Each R expansion reads +, processes T (which prints the next number), prints +, and only then processes the remaining R. Hence the execution order is 9,5,+,2,+, yielding 95+2+, option B. The action is before the recursive R, so it does not postpone both plus signs to the end.

Original paper, page 8

2 marks · MCQ
Report issue

Three-address code from synthesized expression locations

Intermediate Code

Question 59, GATE 2003: A syntax-directed definition uses:
S→id := E {gen(id.place '=' E.place);}
E→E1+E2 {t=newtemp(); gen(t '=' E1.place '+' E2.place); E.place=t;}
E→id {E.place=id.place;}
gen emits code and newtemp returns a fresh temporary t1,t2,... on each call. For X=Y+Z, what three-address code is generated?
A. X=Y+Z
B. t1=Y+Z; X=t1
C. t1=Y; t2=t1+Z; X=t2
D. t1=Y; t2=Z; t3=t1+t2; X=t3
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Reduce identifier Y using E→id: set its place to Y without generating an instruction. Reduce Z the same way, with place Z.
2. At the addition node, call newtemp once to obtain t1. Emit t1=Y+Z and make the addition expression's place t1.
3. At the assignment node, use X as the destination and the completed expression place as source. Emit X=t1.
4. The ordered output is precisely B. No identifier-copy actions occur in the definition, ruling out C and D; the addition action cannot be bypassed to get A.

Solution: An identifier expression uses the identifier’s existing place and emits no copy. The addition allocates one temporary and emits t₁=Y+Z, after which its place is t₁. The assignment then emits X=t₁. Thus the two-instruction sequence in B follows directly; no temporaries are needed merely to refer to Y and Z.

Original paper, page 8

2 marks · MCQ
Report issue

Static scope with call-by-need evaluation

Runtime Environments & Parameter Passing

Question 73, GATE 2003: A hypothetical language permits globals but no nested function declarations:
global int i=100, j=5;
void P(x) {
  int i=10;
  print(x+10);
  i=200;
  j=20;
  print(x);
}
main() { P(i+j); }
If the language uses static scoping and call-by-need, what values are printed?
A. 115,220  B. 25,220  C. 25,15  D. 115,105
Question 73, GATE 2003: A hypothetical language permits globals but no nested function declarations:
global int i=100, j=5;
void P(x) {
  int i=10;
  print(x+10);
  i=200;
  j=20;
  print(x);
}
main() { P(i+j); }
If the language uses static scoping and call-by-need, what values are printed?
A. 115,220  B. 25,220  C. 25,15  D. 115,105
Question 73, GATE 2003: A hypothetical language permits globals but no nested function declarations:
global int i=100, j=5;
void P(x) {
  int i=10;
  print(x+10);
  i=200;
  j=20;
  print(x);
}
main() { P(i+j); }
If the language uses static scoping and call-by-need, what values are printed?
A. 115,220  B. 25,220  C. 25,15  D. 115,105
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. Under static scope the actual expression i+j is bound to the globals visible at the call in main. P's local i does not replace that lexical binding.
2. Call-by-need postpones evaluation until first use and caches its result. At print(x+10), the actual is first demanded: global i+j=100+5=105. The first print is 105+10=115.
3. P then sets its own local i to 200 and global j to 20. Neither assignment changes the cached value 105.
4. The second print reuses that value, giving 105. Therefore D. Recomputing 100+20 would be call-by-name, not call-by-need.

Solution: Under lexical scope the delayed actual expression i+j refers to main's enclosing global bindings, initially 100 and 5. Its first demand evaluates and memoizes 105, so print(x+10) emits 115. Assigning 200 to P's local i and 20 to global j cannot change the already cached actual value. The later print(x) emits 105. Thus D, 115 followed by 105. Call by need evaluates once on first demand; it is not repeated call-by-name evaluation.

Original paper, page 11

2 marks · MCQ
Report issue

Dynamic scope with call-by-name evaluation

Runtime Environments & Parameter Passing

Question 74, GATE 2003: A hypothetical language permits globals but no nested function declarations:
global int i=100, j=5;
void P(x) {
  int i=10;
  print(x+10);
  i=200;
  j=20;
  print(x);
}
main() { P(i+j); }
If the language uses dynamic scoping and call-by-name, what values are printed?
A. 115,220  B. 25,220  C. 25,15  D. 115,105
Question 74, GATE 2003: A hypothetical language permits globals but no nested function declarations:
global int i=100, j=5;
void P(x) {
  int i=10;
  print(x+10);
  i=200;
  j=20;
  print(x);
}
main() { P(i+j); }
If the language uses dynamic scoping and call-by-name, what values are printed?
A. 115,220  B. 25,220  C. 25,15  D. 115,105
Question 74, GATE 2003: A hypothetical language permits globals but no nested function declarations:
global int i=100, j=5;
void P(x) {
  int i=10;
  print(x+10);
  i=200;
  j=20;
  print(x);
}
main() { P(i+j); }
If the language uses dynamic scoping and call-by-name, what values are printed?
A. 115,220  B. 25,220  C. 25,15  D. 115,105
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. Call-by-name reevaluates the actual expression i+j whenever x is used. Under the stipulated dynamic scope, name lookup uses the nearest active bindings.
2. During the first print, P's local i=10 is nearest, while j resolves to global 5. Thus x=15 and x+10=25.
3. The assignments make the active local i=200 and global j=20. The second use reevaluates i+j as 220, rather than retaining 15.
4. The output is 25,220, B. This is specifically the question's dynamic-name interpretation, not lexical capture of main's i.

Solution: In the question's dynamic-scoping, call-by-name model, the actual expression i+j is reevaluated at each use with the active dynamic bindings. At the first print, i is P's local 10 and j is the global 5, so x+10 is 25. P then changes its local i to 200 and global j to 20. The second evaluation of x gives 220. Hence B. This uses the stipulated dynamic-name lookup rather than lexical capture of the actual expression.

Original paper, page 11

1 mark · MCQ
Report issue

Copy-restore and reference parameters

Runtime Environments & Parameter Passing

Question 1.18, GATE 2002: Compare function results under value-result and reference parameter passing. They:
(A) Never differ; (B) Differ when loops are present; (C) Differ in every case; (D) May differ when exceptions are present.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

Step 1: Use an exceptional exit to distinguish parameter mechanisms.

Step 2: Suppose an actual variable initially holds 0 and the function sets its formal to 1 before raising an exception. Reference passing has already changed the actual to 1. Under copy-restore with copying back only at normal return, the actual remains 0. This is a possible difference, not a claim that all calls differ or that exceptions have one universal language-independent copy-out policy.

Conclusion: With reference passing, updates immediately affect the actual argument. With value-result (copy-in/copy-out), they can remain in the local formal until normal return. If an exception exits before copy-out, the visible results can differ, D, under the conventional no-copy-out-on-exception rule. Aliasing can also distinguish these mechanisms; loops alone neither force nor exclude a difference.

Original paper, page 2

Descriptive
Report issue

All parse trees for i+j*k in an ambiguous grammar

Parsing & Syntax Analysis

Question 22(a), GATE 2002: Grammar E→E+E | E*E | id. Original22(a): Construct all parse trees for i+j*k, where i,j,k are identifiers.
Question 22(a), GATE 2002: Grammar E→E+E | E*E | id. Original22(a): Construct all parse trees for i+j*k, where i,j,k are identifiers.
Question 22(a), GATE 2002: Grammar E→E+E | E*E | id. Original22(a): Construct all parse trees for i+j*k, where i,j,k are identifiers.
Tap to enlarge
Answer & solution

Answer: Two parse trees: +(i,*(j,k)) and *(+(i,j),k), with E→id at every identifier leaf. (no official key was published)

With productions E→E+E, E→E*E, E→id, the two full parse trees are:

Tree 1, root addition:
E
├── E
│   └── id(i)
├── +
└── E
    ├── E
    │   └── id(j)
    ├── *
    └── E
        └── id(k)

Tree 2, root multiplication

E
├── E
│   ├── E
│   │   └── id(i)
│   ├── +
│   └── E
│       └── id(j)
├── *
└── E
    └── id(k)

Here id(i), id(j), and id(k) denote the id tokens with those lexemes. Both yields are i + j * k. There are exactly two trees because the root split must be at one of the two operators, and each remaining two-identifier subtree has a unique possible split. Their grouping is i+(j*k) versus (i+j)*k.

Original paper, page 10

Descriptive
Report issue

Operator precedence in the ambiguous expression grammar

Parsing & Syntax Analysis

Question 22(b), GATE 2002: Grammar E→E+E | E*E | id. Original22(b): What precedence, if any, does this grammar impose on * and +?
Question 22(b), GATE 2002: Grammar E→E+E | E*E | id. Original22(b): What precedence, if any, does this grammar impose on * and +?
Question 22(b), GATE 2002: Grammar E→E+E | E*E | id. Original22(b): What precedence, if any, does this grammar impose on * and +?
Tap to enlarge
Answer & solution

Answer: No relative precedence is specified or enforced by this grammar. (no official key was published)

Both + and * are produced by the same nonterminal E, and the grammar allows both i+(j*k) and (i+j)*k for the same token string. It therefore does not enforce multiplication-before-addition or addition-before-multiplication. Saying merely that the operators have equal precedence is also incomplete: the grammar does not enforce associativity, so it does not define a unique parse even under that description. External parser precedence declarations could resolve conflicts, but they are not part of the supplied grammar.

Original paper, page 10

Descriptive
Report issue

An unambiguous LALR(1) expression grammar

Parsing & Syntax Analysis

Question 22(c), GATE 2002: Grammar E→E+E | E*E | id. Original22(c): Modify the grammar to obtain exactly one parse tree per string in the same language and a nonambiguous LALR(1) grammar.
Question 22(c), GATE 2002: Grammar E→E+E | E*E | id. Original22(c): Modify the grammar to obtain exactly one parse tree per string in the same language and a nonambiguous LALR(1) grammar.
Question 22(c), GATE 2002: Grammar E→E+E | E*E | id. Original22(c): Modify the grammar to obtain exactly one parse tree per string in the same language and a nonambiguous LALR(1) grammar.
Tap to enlarge
Answer & solution

Answer: E→E+T | T; T→T*F | F; F→id. (no official key was published)

One replacement grammar is

E → E + T | T
T → T * F | F
F → id
It accepts exactly the original token language id ((+|*) id)*, without introducing parentheses or changing which token strings are allowed. The E/T levels make * bind more tightly than +, and the left-recursive productions make repeated uses of either operator associate left. Thus i+j*k has only the i+(j*k) parse. This standard expression grammar is SLR(1), and hence LALR(1); separating the levels resolves the shift/reduce ambiguity. The original grammar specified no precedence, so multiplication-before-addition and left associativity are a legitimate choice of an unambiguous interpretation, not properties already forced by that grammar.

Original paper, page 10

1 mark · MCQ
Not in GATE 2027 syllabusReport issue

Assigning load addresses and adjusting references

Compiler Phases, Linking & Loading

Question 1.17, GATE 2001: What is the process of assigning actual load addresses and adjusting program address references: assembly, parsing, relocation, or symbol resolution?
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Step 1: Object code can contain address-dependent references expressed relative to an initially assumed location. Loading the program elsewhere requires assigning its actual locations.

Step 2: Address fields or relocation entries are adjusted to match those locations; this operation is relocation, C. Assembly translates symbolic instructions, parsing recognizes syntactic structure, and symbol resolution identifies which definition a name denotes. These can accompany linking/loading but are distinct tasks.

Original paper, page 3

1 mark · MCQ
Report issue

Unambiguity versus derivation order

Parsing & Syntax Analysis

Question 1.18, GATE 2001: Which claim is false? An unambiguous grammar has identical leftmost and rightmost derivations; LL(1) parsing is top-down; LALR is more powerful than SLR; an ambiguous grammar cannot be LR(k) for any k.
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step 1: Unambiguity means each generated string has one parse tree, hence one leftmost derivation and one rightmost derivation. It does not mean those two sequences of intermediate sentential forms are identical.

Step 2: For S→AB,A→a,B→b, the leftmost derivation is S⇒AB⇒aB⇒ab, while the rightmost one is S⇒AB⇒Ab⇒ab. The grammar is unambiguous, yet the derivations differ.

Thus A is false. LL(1) is top-down, LALR recognizes a strictly larger grammar class than SLR, and every LR(k) grammar is unambiguous.

Original paper, page 3

2 marks · MCQ
Report issue

Aliasing under call by reference

Runtime Environments & Parameter Passing

Question 2.17, GATE 2001: Caller variables begin x=10,y=3 and call func1(y,x,x) by reference, then print x,y. The callee’s formals are x,y,z and execute y=y+4; z=x+y+z. Choose 10,3; 31,3; 27,7; or none.
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Step 1: Rename the caller variables X=10,Y=3 to avoid confusing them with formal names. The call func1(Y,X,X) makes formal x alias Y, while both y and z alias the same caller variable X.

Step 2: y=y+4 changes X from 10 to 14. Then z=x+y+z reads 3+14+14=31 and stores 31 in X. Y is never assigned and remains 3.

The caller prints 31 and 3, B. Treating y and z as separate copies would miss the aliasing effect; this is reference-passing pseudocode, not ordinary C scalar call-by-value.

Original paper, page 6

2 marks · MCQ
Report issue

Reference parameters with dynamic scope

Runtime Environments & Parameter Passing

Question 2.19, GATE 2001: Program P2 has outer n=10. Procedure D declares local n=3 and calls W(n). W takes x by reference, increments x, and prints x. Under dynamic scoping, choose output 10,11,3, or none.
Tap to enlarge
Your answer
Answer & solution

Answer: D; the value printed is 4 (no official key was published)

Step 1: The outer n is set to 10, but procedure D declares its own n and sets it to 3. At the call W(n), the actual argument is that active local variable.

Step 2: Reference passing binds W’s x to D’s n. Executing x=x+1 changes it from 3 to 4; print x therefore prints 4. The outer n remains 10.

Since the listed numeric choices are 10,11,3, the answer is none of these, D. The formal binding already identifies the object, so dynamic scope does not redirect x to the outer n.

Original paper, page 6

Descriptive
Report issue

Compute FIRST and FOLLOW

Parsing & Syntax Analysis

Question 16(a), GATE 2001: Start symbol E; productions E→aA | (E), A→+E | *E | ε. Terminals a,(,),+,*.
Question 16(a), GATE 2001: Start symbol E; productions E→aA | (E), A→+E | *E | ε. Terminals a,(,),+,*.
Tap to enlarge
Answer & solution

Answer: FIRST(E)={a,(}; FIRST(A)={+,*,ε}; FOLLOW(E)=FOLLOW(A)={),$}. (no official key was published)

E→aA begins with a; E→(E) begins with (, so FIRST(E)={a,(}. A’s alternatives begin with + and *, or are empty, giving FIRST(A)={+,*,ε}. Put end marker $ into FOLLOW(E) because E is the start symbol. E→(E) adds ) to FOLLOW(E). E→aA puts A at the end, so FOLLOW(E) is included in FOLLOW(A). A→+E and A→*E put E at the end, so FOLLOW(A) is included in FOLLOW(E). Iterating these inclusions reaches the fixed point FOLLOW(E)=FOLLOW(A)={),$}. Neither + nor * follows E in this grammar; those operators start A.

Original paper, page 9

Descriptive
Report issue

Construct the LL(1) parse table

Parsing & Syntax Analysis

Question 16(b), GATE 2001: Start symbol E; productions E→aA | (E), A→+E | *E | ε. Terminals a,(,),+,*.
Question 16(b), GATE 2001: Start symbol E; productions E→aA | (E), A→+E | *E | ε. Terminals a,(,),+,*.
Tap to enlarge
Answer & solution

Answer: E/a→aA; E/(→(E); A/+→+E; A/*→*E; A/)→ε; A/$→ε; all other entries error. (no official key was published)

For a nonnullable right-hand side put its production under its FIRST terminals. For ε use FOLLOW(A). The complete table is:

nonterminal | a | ( | ) | + | * | $
E | E→aA | E→(E) | error | error | error | error
A | error | error | A→ε | A→+E | A→*E | A→ε

Every occupied cell has exactly one production, so this grammar is LL(1). For example, on a+a the parser selects E→aA, matches a, uses A→+E, matches +, selects E→aA, matches a, then uses A→ε at end of input. The end marker is a parser marker, not a terminal in the original alphabet.

Original paper, page 9

Descriptive
Report issue

Translate repeat-until statements

Semantic Analysis & Type Checking

Question 17, GATE 2001: S→repeat S1 until E. S1.code is body code; E.code computes a Boolean into E.varName (1=true,0=false). newlabel() returns a fresh label; gen(s) emits a code line.
Question 17, GATE 2001: S→repeat S1 until E. S1.code is body code; E.code computes a Boolean into E.varName (1=true,0=false). newlabel() returns a fresh label; gen(s) emits a code line.
Tap to enlarge
Answer & solution

Answer: S.code = gen(L+":") || S1.code || E.code || gen("if "+E.varName+" == 0 goto "+L), where L=newlabel(). (no official key was published)

Associate the production with this semantic rule:

L = newlabel();
S.code = gen(L + ":")
         || S1.code
         || E.code
         || gen("if " + E.varName + " == 0 goto " + L);

Here || denotes concatenation of generated code strings, not Boolean OR. The resulting three-address layout is:

L:
    [body code]
    [compute E into t]
    if t == 0 goto L
    [next statement]

The body is before the condition so it runs at least once. A false result repeats; a true result falls through. E.code must be inside the loop because the condition is recomputed after every iteration. A fresh label for each production application avoids collisions when repeats are nested. No explicit exit label is necessary because the successful path falls through.

Original paper, page 9

Descriptive
Report issue

Eliminate direct left recursion

Parsing & Syntax Analysis

Question 18(a), GATE 2001: Grammar S→Sa | Sb | a | b.
Question 18(a), GATE 2001: Grammar S→Sa | Sb | a | b.
Tap to enlarge
Answer & solution

Answer: S→aR | bR; R→aR | bR | ε. (no official key was published)

In the standard transformation S→Sα1 | Sα2 | β1 | β2, choose α1=a, α2=b and β1=a, β2=b. Introduce a new nonterminal R and write S→aR | bR, R→aR | bR | ε. The initial S production contributes one mandatory letter; R generates any remaining sequence of a’s and b’s, including the empty suffix. Thus both grammars generate exactly all nonempty strings over {a,b}. No production now begins with its own left-hand nonterminal, directly or indirectly. The empty string remains excluded from S, as it was in the original grammar.

Original paper, page 10

Descriptive
Report issue

Enumerate parse trees for abab

Parsing & Syntax Analysis

Question 18(b), GATE 2001: Grammar S→aSbS | bSaS | ε; construct all parse trees of abab and determine ambiguity.
Question 18(b), GATE 2001: Grammar S→aSbS | bSaS | ε; construct all parse trees of abab and determine ambiguity.
Tap to enlarge
Answer & solution

Answer: Exactly two parse trees; grammar is ambiguous. (no official key was published)

Step through it (2 derivations)

The root must use S→aSbS because the yield begins with a. Its explicit b can be the b at position 2 or position 4. These exhaust the possibilities. Use S[children] for an ordered parse-tree node; S[ε] is an empty production.

Tree 1: S[a, S[ε], b, S[a, S[ε], b, S[ε]]]
Tree 2: S[a, S[b, S[ε], a, S[ε]], b, S[ε]]

Accessible tree description: in tree 1 the root’s first S is empty and its final S generates ab. In tree 2 its first S generates ba and its final S is empty. Their leftmost derivations are:
S⇒aSbS⇒abS⇒abaSbS⇒ababS⇒abab.
S⇒aSbS⇒abSaSbS⇒abaSbS⇒ababS⇒abab.
The inner two-letter strings ab and ba each have only their direct production with both S children empty. Consequently there are precisely two trees, not merely at least two. Distinct trees with the same terminal yield prove ambiguity.

Original paper, page 10

1 mark · MCQ
Report issue

Meaning of aliasing

Runtime Environments & Parameter Passing

Question 1.16, GATE 2000: Does aliasing mean multiple names for one memory location, equal values, repeated identifiers, or repeated use of a variable?
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step 1: Aliasing occurs when two accessible expressions designate the same storage object. For example, if p=&x, then x and *p refer to the same int.

Step 2: Assigning through either expression changes what the other observes. Two separate variables can hold equal values without aliasing, and the same identifier can name different objects in different scopes.

Thus A, not merely equal contents or repeated spelling.

Original paper, page 2

1 mark · MCQ
Report issue

Lexical tokens in a printf statement

Lexical Analysis

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

Answer: C (no official key was published)

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

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

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

Original paper, page 3

1 mark · MCQ
Report issue

Derivation used by a top-down parser

Parsing & Syntax Analysis

Question 1.19, GATE 2000: For input scanned left to right, does top-down parsing construct a leftmost derivation, its reverse, a rightmost derivation, or a reversed rightmost derivation?
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Step 1: A top-down parser starts from the start symbol and expands grammar symbols to match the input prefix. It expands the leftmost unprocessed nonterminal to produce the next input symbols.

Step 2: These expansions run in the forward direction from start symbol to terminal string, giving a leftmost derivation, A.

A reversed rightmost derivation characterizes standard bottom-up shift-reduce parsing instead.

Original paper, page 3

2 marks · MCQ
Report issue

Precedence encoded in grammar levels

Parsing & Syntax Analysis

Question 2.21, GATE 2000: Given E→E*F|F+E|F and F→F−F|id, which operator-precedence claim is true: * above +; − above *; + and − equal; + above *?
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Step 1: The only grammar productions introducing minus are inside F. Any operand F used by multiplication or addition is therefore formed before the surrounding E-level operation.

Step 2: For example id*id−id must have the minus within the right F, giving id*(id−id), rather than treating minus as an outer E-level operation. Thus minus binds more tightly than multiplication, B.

The E rules do not give a clean unambiguous ordering between + and *; some mixed expressions have multiple parses. F→F−F is itself associative-ambiguous. These ambiguities do not invalidate the separation placing minus at the tighter grammar level.

Original paper, page 6

Descriptive
Report issue

Parse unusual arithmetic precedence

Parsing & Syntax Analysis

Question 19(a), GATE 2000: Grammar/SDTS: E→E1*T {E.val=E1.val*T.val}; E→T {E.val=T.val}; T→F−T1 {T.val=F.val−T1.val}; T→F {T.val=F.val}; F→2 {F.val=2}; F→4 {F.val=4}. Attributes are evaluated immediately after bottom-up reductions. Construct the parse tree for 4−2−4*2 and evaluate it.
Question 19(a), GATE 2000: Grammar/SDTS: E→E1*T {E.val=E1.val*T.val}; E→T {E.val=T.val}; T→F−T1 {T.val=F.val−T1.val}; T→F {T.val=F.val}; F→2 {F.val=2}; F→4 {F.val=4}. Attributes are evaluated immediately after bottom-up reductions. Construct the parse tree for 4−2−4*2 and evaluate it.
Tap to enlarge
Answer & solution

Answer: (4−(2−4))*2 = 12 (no official key was published)

Step through it (19 steps)

The grammar makes subtraction part of T and multiplication part of E. Thus subtraction binds more tightly than multiplication. Moreover T→F−T is right-recursive, so the subtraction chain groups to the right, not to the left. The annotated parse tree is:

E[12]
├── E[6]
│   └── T[6]
│       ├── F[4] → 4
│       ├── −
│       └── T[−2]
│           ├── F[2] → 2
│           ├── −
│           └── T[4]
│               └── F[4] → 4
├── *
└── T[2]
    └── F[2] → 2

Its left-to-right terminal yield is exactly 4−2−4*2. Bottom-up, the innermost T has value 4; its parent computes 2−4=−2; the next T computes 4−(−2)=6. E→T copies 6. The final right T has value 2, so the root computes 6*2=12. Ordinary arithmetic precedence would give a different result; here the supplied grammar, not familiar operator conventions, defines the grouping.

Original paper, page 9

Descriptive
Report issue

Synthesize reduction-count attributes

Semantic Analysis & Type Checking

Question 19(b), GATE 2000: Grammar/SDTS: E→E1*T {E.val=E1.val*T.val}; E→T {E.val=T.val}; T→F−T1 {T.val=F.val−T1.val}; T→F {T.val=F.val}; F→2 {F.val=2}; F→4 {F.val=4}. Attributes are evaluated immediately after bottom-up reductions. Add synthesized attributes to compute E.red, the total reductions without changing the grammar.
Question 19(b), GATE 2000: Grammar/SDTS: E→E1*T {E.val=E1.val*T.val}; E→T {E.val=T.val}; T→F−T1 {T.val=F.val−T1.val}; T→F {T.val=F.val}; F→2 {F.val=2}; F→4 {F.val=4}. Attributes are evaluated immediately after bottom-up reductions. Add synthesized attributes to compute E.red, the total reductions without changing the grammar.
Question 19(b), GATE 2000: Grammar/SDTS: E→E1*T {E.val=E1.val*T.val}; E→T {E.val=T.val}; T→F−T1 {T.val=F.val−T1.val}; T→F {T.val=F.val}; F→2 {F.val=2}; F→4 {F.val=4}. Attributes are evaluated immediately after bottom-up reductions. Add synthesized attributes to compute E.red, the total reductions without changing the grammar.
Tap to enlarge
Answer & solution

Answer: Each production adds 1 to the sum of its nonterminal children’s red attributes; the given input has E.red=10. (no official key was published)

Every nonterminal node in a parse tree represents one use of a grammar production, hence one reduction in a bottom-up parse. A terminal contributes no reduction by itself; F→2 or F→4 contributes one. Preserve all original val actions and append:

E → E1 * T : E.red = E1.red + T.red + 1
E → T      : E.red = T.red + 1
T → F − T1 : T.red = F.red + T1.red + 1
T → F      : T.red = F.red + 1
F → 2      : F.red = 1
F → 4      : F.red = 1

These are synthesized because each left-hand attribute depends only on child attributes. No global counter or inherited attribute is needed. In 4−2−4*2, there are four F reductions, four T reductions (two T→F and two T→F−T), and two E reductions (E→T and E→E*T), totaling 10. One bottom-up production sequence is F→4, F→2, F→4, T→F, T→F−T, T→F−T, E→T, F→2, T→F, E→E*T, understood as reductions from right-hand sides to left-hand sides. Parser accept is not an additional grammar reduction, and any augmented start rule is outside the question’s requested reduction to E.

Original paper, page 9

1 mark · MCQ
Report issue

Relative parser power

Parsing & Syntax Analysis

Question 1.17, GATE 1999: Which parser recognizes the broadest grammar class: LL(1), canonical LR, SLR, or LALR?
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

Canonical LR(1) retains a full lookahead context in its states. SLR instead uses FOLLOW sets for reductions, and LALR merges states sharing LR(0) cores; both simplifications can create conflicts absent from the canonical construction. LL(1) is also a more restrictive deterministic grammar class. Consequently canonical LR is the most powerful among the choices, B. Power here concerns which grammars can be handled without conflicts, not implementation speed or table size.

Original paper, page 2

2 marks · MSQ
Report issue

Dynamic scope through a caller

Runtime Environments & Parameter Passing

Question 2.13, GATE 1999: Global x is set to 0.25. show prints x. small has local x=0.125 and calls show. Main calls show,then small, using dynamic scope.
Question 2.13, GATE 1999: Global x is set to 0.25. show prints x. small has local x=0.125 and calls show. Main calls show,then small, using dynamic scope.
Tap to enlarge
Select all that apply
Answer & solution

Answer: C: 0.25,0.125 (no official key was published)

Dynamic lookup searches active calling environments. In the first show call, no nearer local x is active, so the global value 0.25 is printed. In the second call, small is the active caller and its local x=0.125 is the nearest binding, so show prints 0.125. Thus C. Under lexical scope, show’s definition outside small would instead resolve both calls to the global binding; the explicit dynamic-scoping premise is therefore essential.

Original paper, page 4

2 marks · MSQ
Report issue

Blank-insensitive FORTRAN tokenization

Lexical Analysis

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

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

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

Original paper, page 5

2 marks · MSQ
Report issue

Both left and right recursion

Parsing & Syntax Analysis

Question 2.15, GATE 1999: A grammar is both left and right recursive for a nonterminal. Must it be ambiguous,unambiguous,or is more information required?
Tap to enlarge
Select all that apply
Answer & solution

Answer: C literally; usefulness assumptions matter (no official key was published)

Both recursion directions can certainly occur in an ambiguous grammar: S→Sa|aS|a derives aa using either recursive rule. But the premise alone does not say that the recursive nonterminal is reachable and productive. For example S→c together with A→Aa|aA|b has both recursion directions at A, while the start language has just one parse tree for c. Thus the literal premise does not force ambiguity, giving C. The example deliberately exposes the omitted usefulness condition; it does not assert that an arbitrary useful doubly recursive nonterminal is harmless. The usual ambiguity claim needs a more precise grammar hypothesis.

Original paper, page 5

5 marks · Descriptive
Report issue

Synthesized attributes for binary fractions

Semantic Analysis & Type Checking

Question 9, GATE 1999: Assign synthesized attributes to evaluate a binary numeral, exemplified by 101.101=5.625. The reproduced grammar is damaged: GateForum prints “S → LL\L; L → LB\B; B → 0\1”, with no radix point; GFG has conventional alternative bars but an unclear/missing radix-point glyph. Conditional intended grammar used below: S→L.L | L; L→LB | B; B→0 | 1. Write semantic rules for every production.
Tap to enlarge
Shared context

Assign synthesized attributes to evaluate a binary numeral, exemplified by 101.101=5.625. Conditional intended grammar used below: S→L.L | L; L→LB | B; B→0 | 1. Write semantic rules for every production.

Answer & solution

Answer: For S→L₁.L₂, use S.val=L₁.val+L₂.val/2^(L₂.len); synthesize L.val and L.len. (no official key was published)

a radix-point production is required to parse the supplied fractional example. The following is an explicitly stated reconstruction consistent with that example, not a claim that an official original was verified. If the production is literally S→LL with no point terminal, the grammar does not parse 101.101 at all and is ambiguous about splitting an unmarked bit string.

Use synthesized attributes L.val (the bit string interpreted as an unsigned integer) and L.len (its number of bits). Let B.val be the numeric value of one bit. Distinguish repeated L occurrences by subscripts:

S → L₁ . L₂ : S.val := L₁.val + L₂.val / 2^(L₂.len)
S → L        : S.val := L.val
L → L₁ B     : L.val := 2*L₁.val + B.val; L.len := L₁.len + 1
L → B        : L.val := B.val; L.len := 1
B → 0        : B.val := 0
B → 1        : B.val := 1

Appending a bit shifts the existing integer one binary place left, hence multiplication by two. The fractional substring represents its integer value divided by 2 raised to its length; this also handles leading zeros correctly. All right-hand sides depend only on child attributes, so the definition is S-attributed.

For 101, successive (val,len) pairs are (1,1),(2,2),(5,3). Both L occurrences in 101.101 therefore have (5,3), and S.val=5+5/8=5.625. For 0.001, the fractional attributes (1,3) give 1/8 rather than 1/2, showing why the length attribute is essential.

Original paper, page 7

5 marks · Descriptive
Report issue

Draw activation stacks and static links

Runtime Environments & Parameter Passing

Question 16, GATE 1999: In a Pascal skeleton, program sort declares a,x and the sibling procedures readarray, exchange, qsort. qsort declares k,v and a nested function partition, which declares i,j. The active call sequence is sort → qsort(1,9) → qsort(1,3) → partition(1,3) → exchange(1,3). Draw the runtime stack with access links after each activation.
Tap to enlarge
Answer & solution

Answer: Both qsort frames and exchange link statically to sort; partition links to qsort(1,3). (no official key was published)

Access (static) links follow lexical nesting, whereas control (dynamic) links follow the caller. Label frames S=sort, Q1=qsort(1,9), Q2=qsort(1,3), P=partition(1,3), E=exchange(1,3). Each line below is a complete snapshot written bottom → top; the parenthesized target is the access link:

1. [S(outer/null)]
2. [S(outer/null)] [Q1(S)]
3. [S(outer/null)] [Q1(S)] [Q2(S)]
4. [S(outer/null)] [Q1(S)] [Q2(S)] [P(Q2)]
5. [S(outer/null)] [Q1(S)] [Q2(S)] [P(Q2)] [E(S)]

The final stack, top first, is:
E : static→S; dynamic→P
P : static→Q2; dynamic→Q2
Q2: static→S; dynamic→Q1
Q1: static→S; dynamic→S
S : static→outer/null; dynamic→outer/null

Recursive Q2 is not lexically declared inside Q1, so its static link must not point to Q1. Partition accesses its enclosing qsort variables such as v through Q2, then global a through Q2→S. Exchange was declared directly inside sort, so its a and x references use E→S, even though partition called it. readarray is not active and has no frame in these snapshots. Return addresses and saved registers may also occupy frames but do not change the links.

Original paper, page 8

1 mark · MCQ
Report issue

Parser grammar-class inclusion

Parsing & Syntax Analysis

Question 1.26, GATE 1998: Which is true about SLR, LALR, canonical LR power? C says canonical LR is more powerful than LALR.
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Canonical LR(1) retains separate lookahead contexts. LALR merges LR states with identical LR(0) cores; this can introduce reduce/reduce conflicts that did not exist before merging. SLR uses the still coarser FOLLOW-set reduction rule. Therefore the recognizable grammar classes satisfy SLR⊆LALR⊆canonical LR, with proper inclusions in general, giving C. This compares conflict-free grammar handling, not table compactness or parsing speed.

Original paper, page 3

1 mark · MCQ
Report issue

Where type checking occurs

Semantic Analysis & Type Checking

Question 1.27, GATE 1998: Choose lexical analysis, syntax analysis, syntax-directed translation, or code optimization as the normal type-checking mechanism.
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

Lexical analysis identifies tokens, and parsing checks grammatical structure. Type checking instead propagates and compares semantic attributes: for example, an addition node checks operand types and computes the result type. Syntax-directed definitions or translation rules attach exactly these operations to grammar productions, making C the appropriate option. Optimization can use type information but is not the normal first stage responsible for establishing semantic type compatibility.

Original paper, page 3

1 mark · MCQ
Not in GATE 2027 syllabusReport issue

Relocation constants for concatenated modules

Compiler Phases, Linking & Loading

Question 1.28, GATE 1998: Modules of lengths 200, 800, 600, 500 words are loaded consecutively in that order from zero. Find their relocation constants.
Tap to enlarge
Your answer
Answer & solution

Answer: B: 0, 200, 1000, 1600 (no official key was published)

The first module starts at 0. The next starts after its 200 words, at 200. The third begins after 200+800=1000 words, and the fourth after 200+800+600=1600. These starting addresses are the relocation constants for modules assembled relative to zero. Thus B. The final 500-word length determines the image’s end, not an additional start. A nonzero loading base would add the same base to all four constants.

Original paper, page 3

2 marks · MCQ
Report issue

Nested recursion yielding91

Other / Mixed Topics

Question 2.12, GATE 1998: F(x)=x−10 for x>100, otherwise F(F(x+11)). Evaluate F(95) among 89, 90, 91, 92.
Question 2.12, GATE 1998: F(x)=x−10 for x>100, otherwise F(F(x+11)). Evaluate F(95) among 89, 90, 91, 92.
Tap to enlarge
Your answer
Answer & solution

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

Step through it (21 steps)

First F(100)=F(F(111))=F(101)=91. For x from 95 through 99, x+11 exceeds 100, so F(x+11)=x+1. Hence F(x)=F(x+1) for these five inputs. Chaining gives F(95)=F(96)=…=F(100)=91. Thus C. This local calculation proves the requested value without assuming the more general McCarthy 91 theorem for every input.

Original paper, page 4

2 marks · MCQ
Report issue

Two reference-parameter function calls

Runtime Environments & Parameter Passing

Question 2.13, GATE 1998: In Pascal-like code, f (var x) increments x and returns it. Starting x=5, result=f (x)*f (x). Options 5, 25, 36, 42.
Tap to enlarge
Your answer
Answer & solution

Answer: D: 42 under sequential call evaluation (no official key was published)

The var parameter aliases the caller’s x, so the first completed call changes 5 to 6 and returns 6. The second then changes 6 to 7 and returns 7. Multiplication gives 6·7=42. Choosing the opposite operand first merely swaps these two returned values, leaving the product unchanged. Thus D in the ordinary sequential procedural evaluation model. This is not pass-by-value, which would give 6·6=36. The explanation does not import C’s unsequenced-expression rules into the displayed Pascal-like language.

Original paper, page 5

2 marks · MCQ
Report issue

Constant-time access to lexical ancestors

Runtime Environments & Parameter Passing

Question 2.15, GATE 1998: An array of pointers to activation records used to speed nonlocal variable access is called stack, heap, display, or activation tree?
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

A display stores the current activation-record pointer for each lexical nesting level. A nonlocal variable’s declaration level and fixed offset then identify its address through one indexed display lookup plus the offset. This avoids following a chain of static links through multiple records. The structure is called a display, C. A stack stores records themselves, a heap supports general dynamic allocation, and an activation tree describes call relationships rather than this direct-access table.

Original paper, page 5

Descriptive
Report issue

Eliminate indirect and direct left recursion

Parsing & Syntax Analysis

Question 6(b), GATE 1998: For S→Aa|b and A→Ac|Sd|ε, construct an equivalent grammar with no left recursion and the minimum number of productions. Count each alternative as a production.
Question 6(b), GATE 1998: For S→Aa|b and A→Ac|Sd|ε, construct an equivalent grammar with no left recursion and the minimum number of productions. Count each alternative as a production.
Tap to enlarge
Answer & solution

Answer: A valid six-alternative grammar is S→Ta|bdTa|b; T→cT|adT|ε. Global minimum among arbitrary CFGs is not certified. (no official key was published)

Substitute S→Aa|b into the occurrence S in A→Sd. Then A→Ac|Aad|bd|ε. Each recursive use appends either c or ad on the right; the base is either bd or ε. Thus L(A)=(ε∪{bd}){c,ad}*, and

L(S)={b} ∪ (ε∪{bd}){c,ad}*{a}.

Introduce T generating {c,ad}*. The following equivalent grammar has six individual alternatives:

S → Ta | bdTa | b
T → cT | adT | ε

Every recursive T production starts with a terminal, so it cannot be left recursive. S is not reachable from T, and although S→Ta starts with a nonterminal, its nullable prefix cannot lead back to S. This also rules out indirect left recursion. The first two S alternatives select the two possible prefixes before a word from {c,ad}* and its final a; the third supplies the isolated word b. Conversely, each original derivation has exactly one of these forms, proving language equivalence.

For comparison, the usual mechanical elimination gives S→Aa|b, A→bdT|T, T→cT|adT|ε, with seven alternatives. Inlining A into S removes its two rules and replaces one S alternative by two, saving one production. The six-rule grammar is therefore smaller than that routine result.

The printed requirement “minimum number” needs care. This construction establishes an upper bound of six. It is not a proof that no differently structured, arbitrary CFG can use fewer alternatives. Counting a line with several bars as one “rule” would also give a different metric. The requested global minimum is left uncertified rather than asserted without a lower-bound proof; the equivalent non-left-recursive grammar itself is fully established.

Original paper, page 6

Descriptive
Report issue

LL(1) parsing table

Parsing & Syntax Analysis

Question 22(b), GATE 1998: Construct the LL(1) table for Program→begin d semi X end; X→d semi X | sY; Y→semi sY | ε. Treat begin,d,semi,s,end as terminals.
Question 22(b), GATE 1998: Construct the LL(1) table for Program→begin d semi X end; X→d semi X | sY; Y→semi sY | ε. Treat begin,d,semi,s,end as terminals.
Tap to enlarge
Answer & solution

Answer: Nonempty table entries: Program/begin; X/d,X/s; Y/semi,Y/end. (no official key was published)

Step through it (2 parts)

FIRST(Program)={begin}; FIRST(X)={d,s}; FIRST(Y)={semi,ε}. Program is the start symbol, so FOLLOW(Program)={$}. In Program's production, X is followed by end, hence FOLLOW(X)={end}. The occurrence Y at the end of X→sY gives FOLLOW(Y)={end}; its recursive production adds no new follower.

Fill a production in columns belonging to the FIRST set of its right side. For the ε production, use FOLLOW(Y). The complete non-error entries are:

Nonterminal | lookahead | production
Program     | begin     | Program→begin d semi X end
X           | d         | X→d semi X
X           | s         | X→sY
Y           | semi      | Y→semi sY
Y           | end       | Y→ε

Every other cell, including all cells under $, is an error for these nonterminals. The parsing stack accepts only when both its end marker and the input end marker match after Program is fully processed. There is no conflict: X's alternatives start with different terminals, and FIRST(semi sY)={semi} is disjoint from FOLLOW(Y)={end}. That establishes LL(1), rather than merely presenting a table without explaining why it works.

Original paper, page 8

5 marks · Descriptive
Report issue

Fractional binary attributes

Semantic Analysis & Type Checking

Question 23, GATE 1998: Give synthesized semantic rules for S→L.L|L; L→LB|B; B→0|1, with 101.101=5.625. The dot is visible in the GateForum raster but faint/lost in some extraction.
Tap to enlarge
Answer & solution

Answer: Use integer value and length attributes for the supplied fractional grammar. (no official key was published)

This production parses the fractional example; replacing it by dotless S→LL would describe a different grammar.

Use L.val for the integer represented by its bit string and L.len for its number of bits. All attributes are synthesized:
S→L1 . L2: S.val=L1.val+L2.val/2L2.len
S→L: S.val=L.val
L→L1 B: L.val=2*L1.val+B.val; L.len=L1.len+1
L→B: L.val=B.val; L.len=1
B→0: B.val=0
B→1: B.val=1

Appending a bit shifts the prior number left by one, hence multiplication by two. A fractional bit string of length k represents its integer value divided by 2k. For each 101, (val,len) grows (1,1),(2,2),(5,3); S.val=5+5/8=5.625. The length attribute is necessary: .001 and .1 have the same integer value 1 but represent 1/8 and 1/2 respectively. Every semantic expression uses only child attributes, meeting the synthesized-only requirement. Original official wording has not been established by these secondary copies.

Original paper, page 8

1 mark · MCQ
Report issue

Associativity encoded by recursion

Parsing & Syntax Analysis

Question 1.6, GATE 1997: Grammar X→X⊕Y|Y, Y→Z⊙Y|Z, Z→id. Determine associativity of⊕ and⊙.
Tap to enlarge
Your answer
Answer & solution

Answer: A: ⊕ left, ⊙ right (no official key was published)

In X→X⊕Y, additional⊕ operators are introduced inside the left X. Thus id⊕id⊕id groups as (id⊕id)⊕id. In Y→Z⊙Y, additional⊙ operators occur in the right Y, grouping id⊙id⊙id as id⊙(id⊙id). Therefore⊕ is left associative and⊙ right associative, A. The lower nonterminal level also makes⊙ bind more tightly, but precedence and associativity are distinct properties.

Original paper, page 1

1 mark · MCQ
Report issue

Compiling runtime-sized arrays

Runtime Environments & Parameter Passing

Question 1.8, GATE 1997: A language permits arrays whose sizes are unknown at compile time and requires efficient memory use. Can it be compiled using static allocation, dynamic allocation, or only interpreted?
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

The compiler can generate runtime code that evaluates an array’s size, allocates that much storage and records its address and dimensions. Dynamic allocation therefore handles unknown compile-time sizes while avoiding allocation for an arbitrary worst-case bound, giving C. Interpretation is not necessary: compilation can defer particular operations until runtime. Static allocation alone cannot efficiently reserve exactly the required unknown sizes in the general case.

Original paper, page 1

1 mark · MCQ
Not in GATE 2027 syllabusReport issue

Conditional macro expansion

Compiler Phases, Linking & Loading

Question 1.9, GATE 1997: What does conditional expansion in a macro processor do: runtime tests, conditional runtime expansion, recursion, or choosing statements during macro expansion?
Question 1.9, GATE 1997: What does conditional expansion in a macro processor do: runtime tests, conditional runtime expansion, recursion, or choosing statements during macro expansion?
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

The macro processor evaluates an expansion-time condition, often based on macro arguments or expansion variables, and includes or omits corresponding model statements in the generated text. This occurs while expanding the macro, before the resulting program runs. Therefore D is the matching description. Runtime conditionals instead remain as executable control flow in the expanded program; they do not decide what source text the macro processor generates.

Original paper, page 1

1 mark · MCQ
Report issue

Why a language needs heap storage

Runtime Environments & Parameter Passing

Question 1.10, GATE 1997: Choose the feature motivating heap allocation: recursion, dynamic data structures, dynamic scope, none.
Tap to enlarge
Your answer
Answer & solution

Answer: B / listed item 2 (no official key was published)

Recursion normally creates nested activation lifetimes, which a stack handles. Dynamic scope concerns name lookup and does not itself force arbitrary object lifetimes. General dynamic structures such as linked nodes may be allocated and released in an order unrelated to calls and returns, so they need storage managed outside a strict activation stack: the heap, item 2. This is the conventional distinction. Particular bounded or region-scoped structures could use specialized pools, so “required” refers to supporting general dynamic lifetimes, not every individual dynamic object.

Original paper, page 2

2 marks · MCQ
Report issue

Lexical scope across sibling procedures

Runtime Environments & Parameter Passing

Question 4.8, GATE 1997: A declares x, y. Nested B declares x, z and contains S1; sibling C declares i and contains S2. Which variables are visible?
Question 4.8, GATE 1997: A declares x, y. Nested B declares x, z and contains S1; sibling C declares i and contains S2. Which variables are visible?
Tap to enlarge
Your answer
Answer & solution

Answer: C: S1 sees B.x, z, A.y; S2 sees A.x, A.y, C.i (no official key was published)

Lexical lookup searches the enclosing declaration chain. At S1, the local x in B shadows A’s x; B’s z and A’s y are accessible. At S2, procedure C is a sibling of B, not nested inside B, so B’s x and z are inaccessible. C sees its own i and the x, y declared in A. This is option C. The dynamically most recent caller is irrelevant in this Pascal-like lexical-scope question.

Original paper, page 4

2 marks · MCQ
Not in GATE 2027 syllabusReport issue

One-register evaluation and precedence

Code Generation & Register Allocation

Question 4.9, GATE 1997: For expression prefix (a*b)*c op…where op is+, *, or exponentiation, which operators permit the accumulated product to remain in one register?
Tap to enlarge
Your answer
Answer & solution

Answer: A: + or * under the standard left-to-right accumulator model (no official key was published)

After computing a*b, the single accumulator holds that intermediate value. If op is+or*, ordinary precedence and left associativity allow completing the multiplication by c before moving to the following operation; the accumulator can be reused without spilling a*b. If op is exponentiation, the c-power subexpression binds more tightly and normally must be computed before multiplying by the held a*b, creating a second live intermediate. Thus A in the stated compiler-evaluation model. The omitted suffix and machine instruction set are not fully specified; recomputation or different schedules can change storage requirements, so this is not an architecture-independent impossibility theorem.

Original paper, page 4

5 marks · Descriptive
Report issue

Unambiguous grammar for a Pascal subset

Parsing & Syntax Analysis

Question 22, GATE 1997: A language L is a subset of Pascal with expressions using only + and <, assignment statements, while statements, and compound statements begin ... end. Give an unambiguous grammar. The source does not specify lexical details, empty statements, or a trailing-semicolon convention.
Tap to enlarge
Answer & solution

Answer: Use separate addition/comparison levels, one comparison per expression, and explicit statement/block productions. (no official key was published)

Here is one unambiguous grammar under the conventional choices that + binds more tightly than <, + associates to the left, and < is nonassociative. The lexer supplies tokens id and num; reserved words are distinct tokens, and := is assignment. Start symbol S denotes one statement.

S → id := E | while E do S | begin L end
L → S R
R → ; S R | ε
E → A | A < A
A → A + P | P
P → id | num | ( E )

The grammar deliberately uses nonempty compound statements with semicolons between statements, not after the last one. If empty blocks are required, add the separate production S→begin end. If an optional trailing semicolon is required, replace R by R→ε | ; T and T→ε | S R. These are explicit syntax extensions, not facts supplied by the question.

The expression hierarchy enforces a unique outer operator structure. An unparenthesized < must be the single comparison at the E level, so a+b<c+d parses as (a+b)<(c+d), and a<b<c is rejected unless parentheses explicitly group a comparison. Left recursion at A gives (a+b)+c, not a+(b+c). Parentheses delimit a complete nested expression. At statement level, id, while and begin select disjoint alternatives. The keyword do separates a while condition from its body; matching begin/end delimit a compound body, and semicolons separate its statements. There is no if/else construct and hence no dangling-else ambiguity.

For example, while x<y+1 do begin x:=x+1; y:=y+2 end has a unique parse: its loop body is the entire block, containing two assignments. Static type rules, such as requiring a Boolean while condition and compatible assignment types, belong to semantic analysis rather than this context-free grammar. The source does not uniquely determine every optional Pascal syntax feature; the stated conventions make this proposed grammar precise.

Original paper, page 9

5 marks · Descriptive
Report issue

Typed postfix syntax-directed translation

Semantic Analysis & Type Checking

Question 23, GATE 1997: The grammar is assign-stmt→LHS := E; E→E+T | T; T→T*V | V; V→id | (E); LHS→id. Variables have integer or real types. Convert expressions and assignments to postfix using typed tokens (+,i), (+,r), (*,i), (*,r), (:=,i), (:=,r). give-type(id) and give-name(id) return an identifier's type and name. Give a syntax-directed translation scheme. Mixed-type conversion and narrowing policies are not stated in the source.
Question 23, GATE 1997: The grammar is assign-stmt→LHS := E; E→E+T | T; T→T*V | V; V→id | (E); LHS→id. Variables have integer or real types. Convert expressions and assignments to postfix using typed tokens (+,i), (+,r), (*,i), (*,r), (:=,i), (:=,r). give-type(id) and give-name(id) return an identifier's type and name. Give a syntax-directed translation scheme. Mixed-type conversion and narrowing policies are not stated in the source.
Tap to enlarge
Answer & solution

Answer: Synthesize type and postfix code; choose numeric promotion for each operator, emit left operand then right operand then typed operator, and check assignment compatibility. (no official key was published)

Use synthesized attributes X.type and X.code for E,T,V; use LHS.type and LHS.name for the assignment target. A code value is a token list, and || denotes concatenation. Identifier type is i or r. The following semantic actions specify the traversal without depending on a particular parser implementation.

V→id:       V.type=give-type(id); V.code=[give-name(id)]
V→(E):      V.type=E.type; V.code=E.code
T→V:        T.type=V.type; T.code=V.code
E→T:        E.type=T.type; E.code=T.code
LHS→id:     LHS.type=give-type(id); LHS.name=give-name(id)

For E→E1+T, let t=join(E1.type,T.type), where join(i,i)=i and every other numeric pair gives r. Set E.type=t and E.code=E1.code || T.code || [(+,t)]. For T→T1*V, set t=join(T1.type,V.type), T.type=t and T.code=T1.code || V.code || [(*,t)]. Subscripting E1 and T1 distinguishes the right-hand-side occurrence from the left-hand-side occurrence of the same nonterminal.

For assign-stmt→LHS:=E, check that the expression can be assigned to the destination. Emit [address(LHS.name)] || E.code || [(:=,LHS.type)]. Writing the LHS first follows the conventional postfix assignment form x y (:=,i); the assignment operator consumes the target address and the computed value. In a textual postfix language the name in that first position can denote its address implicitly.

A necessary semantic convention: with precisely the six listed typed operator tokens, the r arithmetic operators must accept integer operands by implicit widening, and (:=,r) must widen an integer value when needed. Under that convention the rules above handle mixed expressions. For integer x,y and real z, the translation of z:=x+y*z is z x y z (*,r) (+,r) (:=,r). Multiplication is emitted first, preserving the grammar's precedence. A real-to-integer assignment is rejected unless an explicit narrowing rule has been authorized.

If the target instead requires both operands already to have the operator's physical type, implicit widening is unavailable. Then replace operand code c by c||[i2r] whenever its integer result is consumed as real, and similarly before assignment to a real target. This alternative introduces an extra conversion token not supplied in the question. Homogeneous expressions need no such extension. Type tags alone do not define a real-to-integer rounding rule or a machine-level cast. Keeping these conventions explicit avoids silently inventing conversion behavior while still giving a complete translation scheme for the stated operator alphabet.

Original paper, page 9

5 marks · Descriptive
Report issue

Five activation records with nested recursion

Runtime Environments & Parameter Passing

Question 24, GATE 1997: Consider this Pascal nesting and call structure, with no calls other than those shown. Main declares X; A, nested in Main, declares Y; B, nested in A, declares Z; C, nested in B, also declares Z. Main calls A; A calls B; B calls C and, after C returns, calls A. C contains no procedure calls. At an instant there are five activation records on the runtime stack. Show its top, static and dynamic links, and local variables. Source skeleton:
program Main; var X: integer;
  procedure A; var Y: integer;
    procedure B; var Z: integer;
      procedure C; var Z: integer;
      begin {no procedure calls} end;
    begin C; A end;
  begin B end;
begin A end.
Ellipses in the source allow other non-call work; the skeleton preserves every shown declaration and call.
Question 24, GATE 1997: Consider this Pascal nesting and call structure, with no calls other than those shown. Main declares X; A, nested in Main, declares Y; B, nested in A, declares Z; C, nested in B, also declares Z. Main calls A; A calls B; B calls C and, after C returns, calls A. C contains no procedure calls. At an instant there are five activation records on the runtime stack. Show its top, static and dynamic links, and local variables. Source skeleton:
program Main; var X: integer;
  procedure A; var Y: integer;
    procedure B; var Z: integer;
      procedure C; var Z: integer;
      begin {no procedure calls} end;
    begin C; A end;
  begin B end;
begin A end.
Ellipses in the source allow other non-call work; the skeleton preserves every shown declaration and call.
Tap to enlarge
Answer & solution

Answer: Bottom to top: Main, A1, B1, A2, B2. Dynamic links follow the call chain; static links B2→A2, A2→Main, B1→A1, A1→Main. (no official key was published)

Distinguish a procedure's lexical parent from the activation that calls it. The dynamic link records the caller; the static link records the active instance of the enclosing lexical scope. Calls to A from inside B are recursive calls to a procedure declared directly inside Main, not declarations of a new A inside B.

Trace the shown calls. Main calls A1, which calls B1. B1's call to C1 creates only the fourth record, and C1 makes no further calls. C1 returns before the following call to A2, so its record has been removed. A2 is then the fourth record, and its call to B2 creates the fifth. At any matching five-record stage of this call pattern, the active chain is therefore:

Stack position   Activation   Local slot   Dynamic link   Static link
TOP              B2           B2.Z         A2             A2
                 A2           A2.Y         B1             Main
                 B1           B1.Z         A1             A1
                 A1           A1.Y         Main           Main
BOTTOM           Main         Main.X       null           null

Other ordinary record fields, such as a return address and saved registers, may exist but are not assigned values by the problem. A1.Y and A2.Y are distinct storage cells, as are B1.Z and B2.Z. No numeric values for X,Y,Z can be recovered from the ellipses. The completed C1 record, including its separate C1.Z slot, is absent.

The dynamic chain is B2→A2→B1→A1→Main. The different static chain from B2 is B2→A2→Main. In particular, A2's static link must not point to B1 merely because B1 called it. To create A2, B1 can follow its own static chain B1→A1→Main to find A's lexical parent. This is the central distinction the example tests.

Original paper, page 10

1 mark · MCQ
Not in GATE 2027 syllabusReport issue

Tasks of a two-pass assembler

Compiler Phases, Linking & Loading

Question 1.17, GATE 1996: Assign object-code generation, adding literals to the literal table, assembly listing generation, and establishing local-symbol addresses to pass 1 or 2.
Tap to enlarge
Your answer
Answer & solution

Answer: B: 2,1,2,1 (no official key was published)

Pass 1 scans source statements, advances the location counter, records labels and collects literals. It therefore establishes local-symbol addresses and enters literals before final machine-code emission. Pass 2 uses those tables to encode instructions, resolve forward uses and produce object code; the final listing can include that generated code. Hence the listed order is 2,1,2,1. If the word resolution refers specifically to substituting a symbol address at its use, that substitution occurs in pass 2; the conventional matching here means establishing the symbol-table address in pass 1.

Original paper, page 3

2 marks · MCQ
Report issue

Ambiguity from a dangling else

Parsing & Syntax Analysis

Question 2.10, GATE 1996: For stmt→if id then stmt | if id then stmt else stmt | id:=id, which listed nested-if statement is ambiguous?
Tap to enlarge
Your answer
Answer & solution

Answer: D: the nested-if statement with one dangling else (no official key was published)

An else following two unfinished nested if statements can attach either to the inner if or to the outer if. These choices produce different parse trees under the given grammar: if p then (if q then s else t), versus if p then (if q then s) else t. Both yield the same token sequence. The nested statement in D has precisely this form. A language implementation may impose “else matches the nearest if,” but that extra convention does not remove ambiguity from the grammar as printed.

Original paper, page 5

2 marks · MCQ
Not in GATE 2027 syllabusReport issue

Termination of recursive macro expansion

Compiler Phases, Linking & Loading

Question 2.16, GATE 1996: Macro M1 recursively invokes M1(X+1) when X=0, otherwise emits WORD X. M2 instead recursively invokes M2(X) when X=0. Which can recurse indefinitely?
Question 2.16, GATE 1996: Macro M1 recursively invokes M1(X+1) when X=0, otherwise emits WORD X. M2 instead recursively invokes M2(X) when X=0. Which can recurse indefinitely?
Tap to enlarge
Your answer
Answer & solution

Answer: A: (ii) only (no official key was published)

For M1 invoked with X=0, the recursive call receives 1. Its condition is then false, so it emits WORD 1 and stops. For any nonzero initial value it stops immediately. M2 invoked with X=0 calls itself with the same argument, so the condition never changes and expansion repeats indefinitely. Thus only the second definition has the nontermination problem, option A. This reasoning uses expansion-time integer parameter evaluation; the recursion is in the macro processor, not a runtime subroutine.

Original paper, page 5

2 marks · MCQ
Not in GATE 2027 syllabusReport issue

Matching translation mechanisms

Compiler Phases, Linking & Loading

Question 2.17, GATE 1996: Match activation record, location counter, reference counts and address relocation with subroutine call, assembler, garbage collection and linking loader.
Tap to enlarge
Your answer
Answer & solution

Answer: D: A–3,B–4,C–2,D–1 (no official key was published)

An activation record stores the state of a subroutine invocation, such as saved control information and local variables. An assembler’s location counter tracks the address assigned to successive statements. Reference counts can support garbage collection by tracking how many references target an object. Address relocation adjusts addresses when a linking loader places program units in memory. These associations give 3,4,2,1 in the listed order. Reference counting has cycle limitations, but it is still the relevant collection mechanism in this matching question.

Original paper, page 6

5 marks · Descriptive
Report issue

Postfix translation by reduction actions

Semantic Analysis & Type Checking

Question 20, GATE 1996: Use the SDTS E→E+E {print “+”}, E→E*E {print “.”}, E→id {print id.name}, E→(E) {no action}. An LR parser executes a production's action immediately after reducing by it. Draw the parse tree and give the translation of (a+b)*(c+d).
Tap to enlarge
Answer & solution

Answer: Literal output ab+cd+. (final dot is emitted); root multiplication with two parenthesized addition subtrees. (no official key was published)

The root production is E→E*E. Its left E derives (E), whose inner E derives E+E with identifier leaves a and b. Its right E derives (E), whose inner E derives E+E with identifier leaves c and d. Thus a textual description of the full parse tree is E(E('(',E(E(id a),'+',E(id b)),')'), '*', E('(',E(E(id c),'+',E(id d)),')')). Parentheses are terminal children of their E→(E) nodes, not emitted characters.

Actions run on reduction, after the right-hand-side subexpressions have been recognized. Reducing id a prints a, reducing id b prints b, and reducing their addition prints +. The parenthesized left operand therefore emits a b +. The E→(E) reduction emits nothing. Similarly the right operand emits c d +. Only after both operand E nodes exist can the root multiplication reduce and print the dot specified by its action.

The literal complete output is a b + c d + ., or ab+cd+. when concatenated without separators. The final dot is an emitted multiplication token, not sentence punctuation. It is postfix notation: each operation follows its operands. As a check, a postfix evaluator pushes a and b, combines them by +, pushes c and d, combines them by +, then multiplies the two resulting values. The grammar is ambiguous in general for unparenthesized mixed operators, but these explicit parentheses fix the intended tree for this particular sentence. Conventional postfix ab+cd+* expresses the same multiplication, but it is not the exact string emitted by the printed SDTS and must not replace it silently.

Original paper, page 9

1 mark · MCQ
Report issue

A dangling else under a false outer test

Parsing & Syntax Analysis

Question 1.4, GATE 1995: Pascal executes X:=−10; Y:=20; if X>Y then if X<0 then X:=abs(X) else X:=2*X. What is X?
Tap to enlarge
Your answer
Answer & solution

Answer: C: −10 (no official key was published)

The outer condition X>Y evaluates as −10>20, which is false. Its entire then statement, including the nested if and its else, is skipped. Therefore neither abs(X) nor doubling executes, and X stays −10. Pascal associates the else with the nearest unmatched if, namely the inner X<0 test. Treating that else as belonging to the outer test would incorrectly execute the doubling branch and obtain −20.

Original paper, page 1

1 mark · MCQ
Not in GATE 2027 syllabusReport issue

Macro definition parameters

Compiler Phases, Linking & Loading

Question 1.11, GATE 1995: In macro Add x,y with body Load y; Mul x; Store y, are x,y variables, identifiers, actual parameters or formal parameters?
Tap to enlarge
Your answer
Answer & solution

Answer: D: formal parameters (no official key was published)

The names x and y appear in the macro definition and stand for values or text supplied by each invocation. They are therefore formal parameters. An invocation such as Add A,B supplies actual parameters A and B, which replace the corresponding formals during expansion. Although formal names are also identifiers in a broad lexical sense, “formal parameters” is the specific role asked here. They need not denote runtime storage variables of the expanded program.

Original paper, page 2

1 mark · MCQ
Report issue

Recognizing a Pascal token without lookahead

Lexical Analysis

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

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

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

Original paper, page 2

1 mark · MCQ
Not in GATE 2027 syllabusReport issue

Information not required in a relocatable object

Compiler Phases, Linking & Loading

Question 1.14, GATE 1995: GFG asks what need NOT be included: object code, relocation bits, exported-symbol names and locations, or absolute addresses of internal symbols. GateForum omits NOT.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

A relocatable object contains machine code plus information allowing its addresses to be adjusted and its external definitions and references resolved. Internal symbol locations can be encoded relative to the module; their final absolute addresses are not known until placement. Therefore absolute addresses of all internal symbols need not be included, D. Object code and relocation/symbol information are the conventional inputs to linking.

Original paper, page 2

2 marks · MCQ
Report issue

A value parameter shadows a global

Runtime Environments & Parameter Passing

Question 2.4, GATE 1995: Pascal has global integer X=2 and procedure FIND(X:real) assigning X:=sqrt(X). After FIND(X), what does printing global X produce?
Tap to enlarge
Your answer
Answer & solution

Answer: A: 2 under the intended Pascal value-parameter program (no official key was published)

Without the keyword var, the procedure parameter is passed by value. Its local X receives a real copy of the argument and shadows the global name inside FIND. Assigning sqrt(X) changes only that local copy; it does not assign to the global integer. On return the global X is still 2, so printing it yields 2. The the paper omits some statement separators; this analysis uses the intended syntactically separated program rather than treating formatting omissions as executable Pascal.

Original paper, page 3

2 marks · MCQ
Not in GATE 2027 syllabusReport issue

String head and tail operations

Other / Mixed Topics

Question 2.9, GATE 1995: For s=acbc, head returns the first character, tail removes it, and concat joins strings. Evaluate concat(head(s),head(tail(tail(s)))).
Tap to enlarge
Your answer
Answer & solution

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

Starting with s=acbc, the first tail is cbc and the second is bc. The head of that second tail is b. Separately head(s)=a. Concatenating a and b gives ab. This follows the nesting from the inside outward; taking only one tail would produce c instead. Among ac,bc,ab,cc, this is option C.

Original paper, page 4

2 marks · MCQ
Report issue

Reduction-time translation

Semantic Analysis & Type Checking

Question 2.10, GATE 1995: Grammar S→xxW {print1}, S→y {print2}, W→Sz {print3}. What is printed by a shift-reduce parse of xxxxyzz?
Tap to enlarge
Your answer
Answer & solution

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

Step through it (14 steps)

The innermost y reduces to S first, printing 2. That S followed by z reduces to W, printing 3. The preceding xx and this W reduce to S, printing 1. The remaining outer z then permits W→Sz, printing another 3, and the remaining outer xxW reduces to S, printing the last 1. Thus the output is 23131. Actions occur after reductions, giving inside-out order rather than the order of productions in a top-down derivation.

Original paper, page 4

2 marks · MCQ
Report issue

Storage of a Pascal variant record

Runtime Environments & Parameter Passing

Question 2.11, GATE 1995: A record has one integer number and alternative fields (x,y:integer) or (p,q:real). With 4-byte integers and 8-byte reals, how much storage for 100 records?
Question 2.11, GATE 1995: A record has one integer number and alternative fields (x,y:integer) or (p,q:real). With 4-byte integers and 8-byte reals, how much storage for 100 records?
Tap to enlarge
Your answer
Answer & solution

Answer: C: 2000 bytes without padding or a stored tag (no official key was published)

Alternative fields share the same region; the record does not store both variants simultaneously. The integer pair needs 8 bytes and the real pair 16, so the variant region must reserve their maximum, 16. Add the common integer field’s 4 bytes to get 20 per record, or 2000 for 100. This assumes the abstract packed/no-padding model and no separately stored discriminant, as the intended choices do. An implementation aligning 8-byte real fields might use 24 bytes per record instead; byte sizes alone do not determine actual ABI padding.

Original paper, page 4

2 marks · MCQ
Report issue

Postfix and addition association

Intermediate Code

Question 2.21, GATE 1995: Convert A+B*(C+D)/F+D*E to postfix using ordinary precedence and left associativity.
Tap to enlarge
Your answer
Answer & solution

Answer: Exact: ABCD+*F/+DE*+; listed B reassociates the additions (no official key was published)

First convert C+D to CD+, multiply by B to obtain BCD+*, and divide by F to obtain BCD+*F/. Ordinary left-associative addition then combines A with that term, before adding DE*, yielding ABCD+*F/+DE*+. Listed B is ABCD+*F/DE*++, which instead parses A+(B*(C+D)/F+D*E). These have the same value over exact arithmetic because addition is associative, explaining the intended B, but they are not identical parse-tree conversions and can differ with floating-point rounding. The distinction is retained rather than labeling the printed postfix exactly left associative.

Original paper, page 5

5 marks · Descriptive
Report issue

Construct a predictive parsing table

Parsing & Syntax Analysis

Question 8, GATE 1995: Construct the LL(1) table for productions: 1 E→−E; 2 E→(E); 3 E→V T; 4 T→−E; 5 T→ε; 6 V→id U; 7 U→(E); 8 U→ε; 9 G→E$. Here E=Expr,T=ExprTail,V=Var,U=VarTail,G=Goal; $ is the end marker.
Tap to enlarge
Answer & solution

Answer: Non-error entries: E: −→1, (→2, id→3; T: −→4, )/$→5; V: id→6; U: (→7, −/)/$→8; G: −/(/id→9. (no official key was published)

FIRST(E)={−,(,id}, FIRST(T)={−,ε}, FIRST(V)={id}, FIRST(U)={(,ε}, and FIRST(G)={−,(,id}. E can be followed by a closing parenthesis in productions 2 and 7, or by $ in production 9. Its appearances at the ends of productions 1 and 4 add no new terminals. Hence FOLLOW(E)=FOLLOW(T)={),$}. From E→VT, FOLLOW(V)={−,),$}; U is at the end of V→idU, so FOLLOW(U)={−,),$}.

Place each nonnullable production under the terminals in its right-hand FIRST set. Place each ε-production under FOLLOW of its left-hand side. The complete table, listing columns in the order −, (, id, ), $, is:
E: [1,2,3,error,error]
T: [4,error,error,5,5]
V: [error,error,6,error,error]
U: [8,7,error,8,8]
G: [9,9,9,error,error].

No cell has two productions, establishing the LL(1) property. Parentheses and the minus token are literal terminals; λ in the source denotes ε, not an input token. If $ is treated as an explicit grammar terminal, a separate meta-end marker follows it, without changing these table choices.

Original paper, page 6

Descriptive
Report issue

Build an arithmetic syntax tree

Intermediate Code

Question 9(a), GATE 1995: Translate a * −(b+c) into an abstract syntax tree.
Tap to enlarge
Answer & solution

Answer: mul(a, neg(add(b,c))) (no official key was published)

The parentheses force addition of b and c first. The minus sign immediately before the parentheses is unary negation, since it has only the parenthesized expression as operand. Multiplication then combines a with that negated result.

The tree is:
        *
       / \
      a  unary−
            |
            +
           / \
          b   c

Equivalently, its exact parenthesized representation is mul(a,neg(add(b,c))). Leaves are identifiers and internal nodes are operations. The abstract syntax tree need not contain separate parenthesis nodes because the tree structure already records grouping. It is important not to turn the unary minus into a binary subtraction with a missing left child. A code generator could evaluate add(b,c), negate its result, and finally multiply by a; the tree expresses that dependency regardless of the eventual instruction order.

Original paper, page 6

Descriptive
Report issue

Resolve Pascal record scopes

Runtime Environments & Parameter Passing

Question 10(a), GATE 1995: procedure T(U,V,X,Y:integer); var A:record A,B:integer end; B:record B,A:integer end; begin with A do begin A:=4; B:=V end; with B do begin A:=X; B:=Y end end. Identify the declarations bound to each A and B occurrence.
Tap to enlarge
Answer & solution

Answer: First with assigns A.A=4 and A.B=V; second assigns B.A=X and B.B=Y. (no official key was published)

There are six distinct declarations with these spellings: two outer record variables, outer A and outer B, and two integer fields inside each record. A field name belongs to its record’s field namespace; declaring field A does not replace the surrounding record variable A.

In “with A do”, the selector A is resolved before entering the with environment, so it denotes the outer record variable A. Within that body, unqualified field identifiers take precedence: the assignment A:=4 means outer-A.A:=4, while B:=V means outer-A.B:=V. V remains the procedure parameter.

That with scope ends at its end. Therefore the selector in the following “with B do” denotes the outer record B, not the field B from the preceding block. Within the second body, A:=X means outer-B.A:=X and B:=Y means outer-B.B:=Y. X and Y are parameters. The field declarations in the first record define A.A and A.B; those in the second define B.B and B.A. Parameter U is unused in the displayed the paper.

Original paper, page 6

Descriptive
Report issue

Distinguish Pascal lexical and syntax errors

Lexical Analysis

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

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

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

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

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

Original paper, page 6

Report issue

Historical FORTRAN storage and recursion

Runtime Environments & Parameter Passing

Question 1.1, GATE 1994: Why did the historical FORTRAN implementations described not permit recursion: static allocation, dynamic allocation, absent hardware stacks, or impossibility on some machines?
Tap to enlarge
Your answer
Answer & solution

Answer: A: static allocation in the historical implementation model (no official key was published)

A single statically allocated location for each local variable provides only one activation’s storage. A recursive call would overwrite values still needed by its caller, so that implementation cannot support general recursion without changing its storage scheme. A stack of activation records is the usual solution; a hardware stack is not essential because software can implement one. Thus A explains the historical restriction. It is not a claim about all modern Fortran: later standards and implementations support recursive procedures with appropriate activation storage.

Original paper, page 1

Not in GATE 2027 syllabusReport issue

Why unrestricted goto is discouraged

Other / Mixed Topics

Question 1.5, GATE 1994: Is unrestricted goto harmful because verification is harder, runtime rises, memory rises, or generated code is necessarily longer?
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

Arbitrary jumps can create tangled control flow with many entry points and difficult-to-track invariants. This makes local reasoning about a block’s preconditions and postconditions harder, so program verification and maintenance suffer. A jump itself need not increase runtime, data storage or machine-code length; those effects depend on the program and compiler. The objection is therefore structural reasoning, not a universal performance penalty. Structured conditionals and loops make control-flow boundaries more explicit.

Original paper, page 1

Report issue

Purpose of an intermediate representation

Intermediate Code

Question 1.12, GATE 1994: Why generate intermediate code for an abstract machine: easier lexing, availability of syntax-directed rules, frontend portability, or inability to generate real machine code directly?
Tap to enlarge
Your answer
Answer & solution

Answer: C: frontend portability (no official key was published)

An intermediate representation separates language analysis from target-machine details. The same frontend can translate a source language into that representation, while different backends generate code for different processors. This improves portability and reuse. Direct generation of machine code is possible, so D is false. Syntax-directed translation can generate an IR, but its existence is not the main abstract-machine benefit, and lexical analysis does not become fundamentally easier merely because an IR is chosen.

Original paper, page 2

Report issue

A context-sensitive language check

Semantic Analysis & Type Checking

Question 1.18, GATE 1994: Which feature cannot generally be enforced by a CFG alone: if-then-else syntax, recursive-procedure syntax, declaration before variable use, or arbitrary-length variable names?
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

A CFG can describe nested statements, recursive syntactic structures and identifier shapes of unbounded length. Checking that a particular identifier was previously declared requires matching that name against the declarations valid in its scope, not merely recognizing a syntactic category. Compilers therefore use symbol tables and semantic analysis for this context-sensitive condition. The claim concerns unrestricted identifiers and general programs; a finite fixed universe could be encoded into a much larger grammar, but that is not the usual language model.

Original paper, page 2

Report issue

Call by name versus call by reference

Runtime Environments & Parameter Passing

Question 1.20, GATE 1994: Which argument can expose different results between call-by-name and call-by-reference: constant, array address, whole array, or an array element?
Tap to enlarge
Your answer
Answer & solution

Answer: D (array element) (no official key was published)

For an actual argument a[i], call-by-reference fixes the target location at call time. Call-by-name reevaluates the argument expression each time the formal is used. For example start i=1 and call a procedure whose body sets i:=2 then assigns 9 to the formal. Reference modifies a[1], while name modifies a[2]. Thus an array element whose index can change demonstrates the difference.

Original paper, page 3

Report issue

Matching compiler formalisms

Compiler Phases, Linking & Loading

Question 3.5, GATE 1994: Match BNF, lexical analysis, YACC and recursive-descent parsing with general CFGs, regular expressions, LALR(1), LL(1).
Question 3.5, GATE 1994: Match BNF, lexical analysis, YACC and recursive-descent parsing with general CFGs, regular expressions, LALR(1), LL(1).
Tap to enlarge
Answer & solution

Answer: i–d,ii–a,iii–b,iv–c (no official key was published)

Backus–Naur form is a notation for context-free grammar productions. Lexical token patterns are commonly specified by regular expressions and recognized by finite automata. Traditional YACC constructs an LALR(1) parser. A predictive recursive-descent parser uses LL(1) choices, with one-token lookahead selecting a production. Thus the requested mapping is d,a,b,c. General recursive descent can also use backtracking or more lookahead, so the LL(1) match refers to its standard nonbacktracking predictive form.

Original paper, page 4

Descriptive
Report issue

Coroutines and subroutines

Runtime Environments & Parameter Passing

Question 17(a), GATE 1994: State true or false with reason: A coroutine is just another name for a subroutine.
Question 17(a), GATE 1994: State true or false with reason: A coroutine is just another name for a subroutine.
Tap to enlarge
Answer & solution

Answer: False. (no official key was published)

1. An ordinary subroutine is entered by a call and returns control to its caller; a fresh call normally begins execution at its entry point.

2. A coroutine can suspend at a yield/resume point, preserve its execution context, and later continue from that point. Control may transfer cooperatively between peer coroutines.

3. One can implement coroutines using lower-level mechanisms, but the two terms do not name the same control-flow abstraction.

Original paper, page 6

Descriptive
Report issue

Two-pass assembler tables

Compiler Phases, Linking & Loading

Question 17(b), GATE 1994: State true or false with reason: A two-pass assembler uses its machine opcode table in the first pass of assembly.
Question 17(b), GATE 1994: State true or false with reason: A two-pass assembler uses its machine opcode table in the first pass of assembly.
Tap to enlarge
Answer & solution

Answer: True for the conventional two-pass assembler. (no official key was published)

1. Pass one assigns addresses and builds the symbol table. To advance the location counter correctly, it must recognize instructions and determine their lengths.

2. The machine opcode table supplies instruction classification and length information, so it is consulted before final code generation in pass two.

3. Using the table does not mean final object code or unresolved operand addresses must already be emitted during pass one.

Original paper, page 6

Descriptive
Report issue

Macros versus callable subroutines

Compiler Phases, Linking & Loading

Question 18(a), GATE 1994: State true or false with reason: A subroutine cannot always be used to replace a macro in an assembly-language program.
Question 18(a), GATE 1994: State true or false with reason: A subroutine cannot always be used to replace a macro in an assembly-language program.
Tap to enlarge
Answer & solution

Answer: True. (no official key was published)

1. A macro performs assembly-time text expansion. Its parameters may select register names, opcodes, labels, data declarations or conditional assembly. Such choices can alter the generated instruction sequence itself.

2. A subroutine is runtime code reached by a call; it has call/return and argument conventions rather than general assembly-time substitution. A macro that declares a label or storage at each expansion point cannot be replaced simply by calling one fixed subroutine.

3. Some computational macros can be rewritten as subroutines, but that limited case does not justify the universal replacement claim.

Original paper, page 6

Descriptive
Report issue

External symbol resolution

Compiler Phases, Linking & Loading

Question 18(b), GATE 1994: State true or false with reason: A symbol declared external in assembly language is assigned an address outside the program by the assembler itself.
Question 18(b), GATE 1994: State true or false with reason: A symbol declared external in assembly language is assigned an address outside the program by the assembler itself.
Tap to enlarge
Answer & solution

Answer: False. (no official key was published)

1. External means the definition is supplied by another object module or library, not defined in this assembly unit.

2. The assembler records an unresolved external reference and the necessary relocation/linkage information.

3. The linker, or a loader performing dynamic resolution, combines definitions and assigns/resolves the final address. The assembler alone generally lacks the required placement and definition information.

Original paper, page 6

Descriptive
Report issue

Lexical scope in sibling procedures

Runtime Environments & Parameter Passing

Question 22(i), GATE 1994: main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under static scoping?
Question 22(i), GATE 1994: main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under static scoping?
Question 22(i), GATE 1994: main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under static scoping?
Question 22(i), GATE 1994: main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under static scoping?
Tap to enlarge
Answer & solution

Answer: 2, 2, 2 (without separators, 222). (no official key was published)

Static, or lexical, scoping resolves a name by the nesting of declarations in the program text, not by whichever procedure happened to call the current procedure. Procedure two has no local declaration of r. Its immediately enclosing lexical scope is main, so every reference to r in two denotes main's r. Procedure one's local r is in a sibling procedure's scope and is not visible inside two.

After main assigns r=2, its first call to two prints 2. Next main calls one, which creates a separate local r and sets that local variable to 5. The call from one to two still resolves two's r to main's unchanged variable and therefore prints 2. Returning from one removes its local activation without changing main's r. The final direct call to two again prints 2.

Thus the sequence of values is 2,2,2. The pseudocode uses write rather than writeln and requests no separators, so a literal output stream would commonly appear as 222. Formatting conventions do not change the three values.

Original paper, page 6

Descriptive
Report issue

Dynamic scope follows the call chain

Runtime Environments & Parameter Passing

Question 22(ii), GATE 1994: main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under dynamic scoping?
Question 22(ii), GATE 1994: main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under dynamic scoping?
Question 22(ii), GATE 1994: main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under dynamic scoping?
Question 22(ii), GATE 1994: main declares global integer r. Procedure two, declared directly inside main, executes write(r). Sibling procedure one declares its own local r, assigns it 5, then calls two. main assigns its r=2 and executes two; one; two. What values are printed under dynamic scoping?
Tap to enlarge
Answer & solution

Answer: 2, 5, 2 (without separators, 252). (no official key was published)

Under dynamic scoping, resolve an unbound local name by searching active callers, nearest first. Procedure two itself has no r. In the first call main→two, the closest active declaration is main's r, already set to 2, so two prints 2.

The second relevant call chain is main→one→two. Procedure one has an active local r initialized to 5. The search from two finds that declaration before reaching main, so this invocation prints 5. Procedure two merely reads the variable; it does not copy the value into main's r or assign to either declaration.

After one returns, its local r is no longer in the active call chain. The last main→two call therefore finds main's original r=2 and prints 2. The resulting sequence is 2,5,2, or 252 if ordinary write operations introduce no spaces. The key distinction is lifetime plus dynamic caller order: the same body of two can access different storage on different calls under dynamic scoping, whereas static scoping would always bind its r to main's lexical declaration. This result concerns the hypothetical dynamic-scoping interpretation requested, not the default rules of Pascal.

Original paper, page 6

5 marks · Descriptive
Not in GATE 2027 syllabusReport issue

A complete one-register translation scheme

Code Generation & Register Allocation

Question 23, GATE 1994: Generate code for A→id:=E; E→E+T | T; T→(E) | id. The target has one accumulator R and only LOAD x (R:=mem[x]), STORE x (mem[x]:=R), ADD x (R:=R+mem[x]). Provide a syntax-directed translation.
Tap to enlarge
Answer & solution

Answer: Use synthesized code/place attributes and a fresh memory temporary for each addition; assign by LOAD expression.place; STORE target. (no official key was published)

Give every E and T synthesized attributes code (an instruction list) and place (a memory address containing its value). An identifier token has its declared address id.addr. Let newtemp() allocate a fresh, non-aliasing memory cell and || concatenate instruction lists. The following bottom-up semantic rules form a complete syntax-directed definition.

T→id: T.code=[]; T.place=id.addr.
T→(E): T.code=E.code; T.place=E.place.
E→T: E.code=T.code; E.place=T.place.
E→E1+T: choose t=newtemp(); E.code=E1.code || T.code || [LOAD E1.place, ADD T.place, STORE t]; E.place=t.
A→id:=E: A.code=E.code || [LOAD E.place, STORE id.addr].

The invariant is that executing a subtree's code leaves its value in its designated memory cell. Identifier leaves already satisfy this. Parentheses and E→T preserve it. In an addition, both operands are available in memory after their code has run; LOAD fetches the left one and ADD combines the right one without needing a second register. STORE preserves the result for enclosing expressions. Fresh temporaries prevent a right subtree from overwriting the saved left value. The final assignment changes the target only after the whole expression has been evaluated, so x:=x+y also works.

For x:=a+(b+c), first emit LOAD b; ADD c; STORE t1. Then LOAD a; ADD t1; STORE t2. Finally LOAD t2; STORE x. This deliberately simple scheme may contain redundant loads/stores, but optimization is not required. It uses exactly the three allowed instruction types and handles arbitrary nesting, unlike a scheme that leaves an unprotected partial result only in R.

Original paper, page 7

Report issue

FORTRAN77 keywords as identifiers

Lexical Analysis

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

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

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

Original paper, page 1

Report issue

FORTRAN mixed arithmetic and integer assignment

Semantic Analysis & Type Checking

Question 2.5, GATE 1993: For X=4.0, evaluate integer I assigned −2**2+(5.0*X)/(X*3)+3/4, following the displayed fraction grouping.
Tap to enlarge
Answer & solution

Answer: −2 (no official key was published)

Exponentiation binds before unary negation, so −2**2 is −4, not +4. The middle term is real arithmetic: 20.0/12.0=5/3. The literal operands in 3/4 are integers, so FORTRAN integer division gives zero. The resulting real value is −4+5/3=−7/3. Assignment to integer I truncates toward zero, yielding −2. The printed source uses two-dimensional fractions rather than literal FORTRAN source; the grouping in the paraphrase is stated explicitly so a flattened division/multiplication expression is not silently substituted.

Original paper, page 2

2 marks · MSQ
Report issue

Aliased reference parameters with a shadowed local

Runtime Environments & Parameter Passing

Question 7.1, GATE 1993: Global m=0. P(var x,y:integer) has its own local m, sets that local m:=1, then x:=y+1. What is printed after P(m,m)?
Question 7.1, GATE 1993: Global m=0. P(var x,y:integer) has its own local m, sets that local m:=1, then x:=y+1. What is printed after P(m,m)?
Tap to enlarge
Select all that apply
Answer & solution

Answer: D: 1 because x and y both reference the global m (no official key was published)

Both formal reference parameters bind to the caller’s global m. The procedure’s separate local variable named m shadows the global name only for direct uses of that identifier in P; setting it to one does not change the caller’s m. Then x:=y+1 reads global m=0 through y and stores one through x. Consequently the global m printed by the caller is one. The result is not caused by the local m assignment, so the option giving that incorrect reason is not selected.

Original paper, page 6

2 marks · MSQ
Report issue

A value parameter does not modify its actual expression

Runtime Environments & Parameter Passing

Question 7.2, GATE 1993: Global n=0. Q(x:integer;var y:integer) executes x:=y+1. What is printed after Q(n*1,n)?
Question 7.2, GATE 1993: Global n=0. Q(x:integer;var y:integer) executes x:=y+1. What is printed after Q(n*1,n)?
Tap to enlarge
Select all that apply
Answer & solution

Answer: B: 0 (no official key was published)

The actual n*1 is evaluated to zero and copied into value parameter x. Parameter y is a reference to n. The assignment computes y+1=1 but writes only the local copy x; it never assigns to y. Thus n remains zero and the caller prints zero. Calling with an expression as the first actual is valid precisely because that parameter has value semantics; a reference formal would require a suitable variable location instead.

Original paper, page 6

2 marks · MSQ
Report issue

Scope and shadowing of a global name

Runtime Environments & Parameter Passing

Question 7.3, GATE 1993: Global m is declared in PARAM. P declares another local m; Q does not. Where is the global name m directly visible?
Question 7.3, GATE 1993: Global m is declared in PARAM. P declares another local m; Q does not. Where is the global name m directly visible?
Tap to enlarge
Select all that apply
Answer & solution

Answer: C: PARAM and Q (no official key was published)

Lexical lookup in P finds its local m before reaching the enclosing declaration, so unqualified m there denotes the local variable. In Q, which has no local m, lookup reaches the global declaration in PARAM. The same global name is visible in the main block itself. Hence PARAM and Q are the regions of direct visibility, C. The global object can still be accessed indirectly through P’s reference parameters; object accessibility is distinct from whether its identifier is shadowed.

Original paper, page 6

2 marks · MSQ
Report issue

Addition-subtraction swap

Other / Mixed Topics

Question 7.4, GATE 1993: What do a:=a+b; b:=a−b; a:=a−b accomplish for initialized integer variables?
Tap to enlarge
Select all that apply
Answer & solution

Answer: A: exchange a and b, assuming no overflow (no official key was published)

Let the initial values be a0,b0. After the first statement a=a0+b0. The second computes b=(a0+b0)−b0=a0. The final statement gives a=(a0+b0)−a0=b0, completing the swap without a separate temporary. This derivation assumes the intermediate sum is representable or a defined modular arithmetic model. The snippet declares variables but does not initialize them; as a standalone program it would not define starting values. Its intended transformation concerns values supplied before this segment.

Original paper, page 7

2 marks · MSQ
Report issue

Nil pointer dereference

Semantic Analysis & Type Checking

Question 7.5, GATE 1993: Pascal allocates ptr, assigns ptr:=nil, then attempts ptr^.d:=5.2 and prints the reproduced text write ln(ptr). Which error claims are justified?
Tap to enlarge
Select all that apply
Answer & solution

Answer: B, D (runtime nil dereference); as printed, A (compile-time error) also applies (no official key was published)

After new(ptr), assigning nil discards the usable pointer. Dereferencing ptr^ then attempts to access a nonexistent record, so a checked execution reports nil-pointer dereference rather than printing 5.2. This supports the intended runtime-error and nil-error choices B,D. Those issues can cause compile-time rejection before runtime. No claim that the literal program necessarily reaches the dereference is made.

Original paper, page 7

2 marks · MSQ
Not in GATE 2027 syllabusReport issue

First pass of a two-pass assembler

Compiler Phases, Linking & Loading

Question 7.6, GATE 1993: Which first-pass tasks apply: allocate literal space,compute program length,build symbol table,generate load/store machine code?
Tap to enlarge
Select all that apply
Answer & solution

Answer: A,B,C in the standard assembler model (no official key was published)

Pass one tracks the location counter and instruction/data sizes. It assigns addresses to labels, records symbol values, and determines the total layout and length. Literal-pool placement also reserves space and assigns literal addresses when the pool is processed. Final instruction encoding is normally deferred to pass two, when forward symbol references can be resolved, so generating all load/store code is not a standard first-pass task. The answer assumes the ordinary two-pass design, not a hybrid implementation that opportunistically emits some instructions early.

Original paper, page 7

Descriptive
Report issue

Grammar for small Pascal statements

Parsing & Syntax Analysis

Question 25(a), GATE 1993: Construct an ordinary CFG for assignment id:=expression, for id:=expression to expression do statement, and begin statement;…;statement end. expression is already defined. Do not use EBNF optional brackets or star.
Question 25(a), GATE 1993: Construct an ordinary CFG for assignment id:=expression, for id:=expression to expression do statement, and begin statement;…;statement end. expression is already defined. Do not use EBNF optional brackets or star.
Tap to enlarge
Answer & solution

Answer: S→id := E | for id := E to E do S | begin L end; L→S | S ; L. (no official key was published)

Let S denote a statement, L a nonempty statement list, E the given expression nonterminal, and id an identifier token. Use:
S → id := E
S → for id := E to E do S
S → begin L end
L → S
L → S ; L

The first production recognizes assignments. The second has a statement as its body, permitting either a single assignment, another loop, or a block. The third encloses a list in begin/end. The two L productions generate exactly one or more statements separated by semicolons, without a trailing semicolon. They replace the informal ellipsis with ordinary CFG recursion; no repetition operator or optional metasyntax is used.

For any finite list length k≥1, apply L→S;L exactly k−1 times and finish with L→S. Conversely each derivation has precisely that separator structure. An empty block is not explicitly requested; if the language separately permits begin end, add an epsilon-list production as an explicit extension rather than silently changing the language. Expression syntax is delegated to the provided E grammar.

Original paper, page 14

Descriptive
Report issue

Parse a for-loop block

Parsing & Syntax Analysis

Question 25(b), GATE 1993: Using S→id:=E | for id:=E to E do S | begin L end and L→S | S;L, draw the parse tree for: for j:=2 to 10 do begin x:=expr1; y:=expr2 end.
Question 25(b), GATE 1993: Using S→id:=E | for id:=E to E do S | begin L end and L→S | S;L, draw the parse tree for: for j:=2 to 10 do begin x:=expr1; y:=expr2 end.
Question 25(b), GATE 1993: Using S→id:=E | for id:=E to E do S | begin L end and L→S | S;L, draw the parse tree for: for j:=2 to 10 do begin x:=expr1; y:=expr2 end.
Tap to enlarge
Answer & solution

Answer: Root loop S, body block S, two assignment statements linked by L→S;L. (no official key was published)

The outermost construct is the for production, not a sequencing block. Its body is one statement S expanded as begin L end. Inside that block the list has two assignments, so its first L uses S;L and its final L uses S.

S
├─for
├─id(j)
├─:=
├─E(2)
├─to
├─E(10)
├─do
└─S
  ├─begin
  ├─L
  │ ├─S
  │ │ ├─id(x)
  │ │ ├─:=
  │ │ └─E(expr1)
  │ ├─;
  │ └─L
  │   └─S
  │     ├─id(y)
  │     ├─:=
  │     └─E(expr2)
  └─end

Reading leaves left to right gives exactly the requested token sequence. The E subtrees are abbreviated because the expression grammar was stipulated as already defined; 2 and 10 are constant expressions and expr1/expr2 stand for their expression subtrees. The semicolon separates the two assignments, while begin/end make both assignments part of a single loop body.

Original paper, page 14

Descriptive
Report issue

Passing reference and value parameters

Runtime Environments & Parameter Passing

Question 26(a), GATE 1993: Procedure P(var x:integer; y:integer) is called as P(a,b). What is pushed on the argument stack for a and b?
Question 26(a), GATE 1993: Procedure P(var x:integer; y:integer) is called as P(a,b). What is pushed on the argument stack for a and b?
Tap to enlarge
Answer & solution

Answer: Address of a for x; current integer value of b for y. (no official key was published)

The var qualifier gives x reference semantics: P must be able to access and modify the caller's actual variable a. Therefore pass a's storage address, not merely its current contents. The unqualified integer y is a value parameter, so evaluate b and push a copy of its current integer value.

After entry, assigning to x changes a because x denotes a through the supplied reference. Assigning to y changes only the callee's copy, leaving b unchanged. Passing the address of b for y would instead implement reference semantics; passing only a's value for x would lose the required alias to the caller's variable.

The question concerns argument payloads, not a complete activation-record layout. Return addresses, saved links and registers may also occupy the stack, but their presence does not change these two payloads. Argument order and stack growth direction depend on the calling convention and are not specified, so no particular push order or numeric offsets should be invented.

Original paper, page 14

Descriptive
Report issue

Addressing formal parameters

Runtime Environments & Parameter Passing

Question 26(b), GATE 1993: Procedure P(var x:integer; y:integer) receives the address of actual a and value of actual b on its stack. How does generated addressing for x differ from y?
Question 26(b), GATE 1993: Procedure P(var x:integer; y:integer) receives the address of actual a and value of actual b on its stack. How does generated addressing for x differ from y?
Question 26(b), GATE 1993: Procedure P(var x:integer; y:integer) receives the address of actual a and value of actual b on its stack. How does generated addressing for x differ from y?
Tap to enlarge
Answer & solution

Answer: x uses an indirect load/store through its pointer slot; y uses its own value slot directly. (no official key was published)

With a frame pointer FP and symbolic offsets ox,oy, the slot at FP+ox contains an address, whereas the slot at FP+oy contains an integer. To read x, first load ptr:=memory[FP+ox], then load memory[ptr]. To assign x:=v, store v into memory[ptr]. These operations reach the caller's a.

To read y, load memory[FP+oy] directly. To assign y:=v, store v into that same local argument slot. This changes the callee's copied value, not b. Thus reference-parameter access has one extra level of indirection relative to a direct stack-slot value parameter, even if a machine's addressing modes combine the micro-operations in one instruction.

The offsets remain symbolic because the source specifies neither stack layout nor saved control fields. If the compiler caches a parameter in a register, it must preserve the same observable aliasing behavior; such optimization does not change the semantic distinction being asked about.

Original paper, page 14

Report issue

Why macro expansion precedes final assembly

Compiler Phases, Linking & Loading

Question 1(vii), GATE 1992: Why expand macros in pass one rather than pass two?
Question 1(vii), GATE 1992: Why expand macros in pass one rather than pass two?
Tap to enlarge
Answer & solution

Answer: Expansion changes code size and the addresses needed for the symbol table (no official key was published)

A macro invocation can expand into several instructions, data definitions and labels. Pass one must account for their sizes to advance the location counter correctly and assign addresses to all later symbols. Deferring expansion until after that layout would invalidate those addresses or require another layout pass. Thus the standard macro assembler expands before or during its first layout pass. A separately implemented macro preprocessor can perform the same work before the nominal assembler passes; the essential requirement is expansion before final address assignment.

Original paper, page 1

Report issue

Instruction location counter

Compiler Phases, Linking & Loading

Question 1(viii), GATE 1992: What is the purpose of an assembler’s instruction location counter?
Question 1(viii), GATE 1992: What is the purpose of an assembler’s instruction location counter?
Tap to enlarge
Answer & solution

Answer: Track the address assigned to the next instruction or data item (no official key was published)

The location counter starts from the selected origin and advances by each assembled instruction or reserved data size. A label encountered at a statement is assigned the current location, enabling the symbol table to record its address. Directives such as ORG can change the counter explicitly. This is a compile/assembly-time layout variable, not the processor’s runtime program counter. Its final difference from the origin can also help determine section length, subject to separate sections and origin changes.

Original paper, page 1

Report issue

FOLLOW sets with damaged option names

Parsing & Syntax Analysis

Question 2(xiii), GATE 1992: FOLLOW(A) uses arbitrary sentential forms; LFOLLOW/RFOLLOW restrict to leftmost/rightmost forms. Both sources lose the L/R prefixes in choices A/B. Determine valid semantic relationships.
Question 2(xiii), GATE 1992: FOLLOW(A) uses arbitrary sentential forms; LFOLLOW/RFOLLOW restrict to leftmost/rightmost forms. Both sources lose the L/R prefixes in choices A/B. Determine valid semantic relationships.
Tap to enlarge
Select all that apply
Answer & solution

Answer: Option letters unresolved; LFOLLOW may differ, and RFOLLOW=FOLLOW under a productive-grammar convention (no official key was published)

Restricted derivations yield subsets of the ordinary FOLLOW set. For S→AB, A→a, B→b, ordinary and rightmost derivations expose Ab, so b belongs to FOLLOW(A) and RFOLLOW(A). Leftmost derivations must expand A before B, so LFOLLOW(A) is empty. This refutes the choices asserting all three always identical or all three always different. For productive grammars, rightmost derivations can realize the needed right context, giving RFOLLOW=FOLLOW. Without that convention, S→XB, X→Ab, B→B gives FOLLOW(A) containing b but no rightmost occurrence of A. Since A/B repeat the unqualified name FOLLOW in both copies, their intended exact comparisons and letters are not reconstructed silently.

Original paper, page 3

Report issue

SLR versus LALR table entries

Parsing & Syntax Analysis

Question 2(xiv), GATE 1992: For one CFG, compare SLR(1) and LALR(1) tables: goto parts may differ; shifts identical; reductions may differ; errors may differ.
Question 2(xiv), GATE 1992: For one CFG, compare SLR(1) and LALR(1) tables: goto parts may differ; shifts identical; reductions may differ; errors may differ.
Tap to enlarge
Select all that apply
Answer & solution

Answer: B, C, D under aligned LR(0)-core state numbering (no official key was published)

Both constructions use the same LR(0) cores for transitions, so terminal shifts and nonterminal gotos coincide when corresponding states are identified. SLR places a completed A production on every token in FOLLOW(A). LALR instead uses the lookaheads propagated to that completed item, often a smaller set. Thus a cell that is a reduction or conflict in SLR may be an error or a different action set in LALR. Therefore shifts are identical but reduction/error entries may differ. Renaming state numbers does not count as a structural goto difference; conflict-resolution policies are separate from raw table construction.

Original paper, page 3

Descriptive
Report issue

A recursive macro that fails to progress

Compiler Phases, Linking & Loading

Question 3(i), GATE 1992: M1 calls M1(X+1) when X=0 and otherwise emits WORD X; M2 calls M2(X) when X=0 and otherwise emits WORD X+1. Which loops forever, and give a call.
Question 3(i), GATE 1992: M1 calls M1(X+1) when X=0 and otherwise emits WORD X; M2 calls M2(X) when X=0 and otherwise emits WORD X+1. Which loops forever, and give a call.
Tap to enlarge
Answer & solution

Answer: M2 0 (no official key was published)

For M1 0, the recursive invocation receives 1. Its zero test fails, so it emits a word and stops; a nonzero initial argument likewise stops directly. In M2 0, the recursive call receives exactly 0 again, so every expansion repeats the same zero test and invocation with no progress. This causes unbounded expansion until a practical processor limit intervenes. The nonzero WORD branch cannot rescue that call because it is never reached. The analysis assumes expansion-time arithmetic and equality tests on X as intended.

Original paper, page 4

Report issue

Object generation pass

Compiler Phases, Linking & Loading

Question 3(ii.a), GATE 1992: In a conventional two-pass assembler, in which pass is object code generated?
Question 3(ii.a), GATE 1992: In a conventional two-pass assembler, in which pass is object code generated?
Question 3(ii.a), GATE 1992: In a conventional two-pass assembler, in which pass is object code generated?
Tap to enlarge
Answer & solution

Answer: Pass2 (no official key was published)

Pass1 establishes layout and collects symbol addresses, including forward definitions not yet known at their first use. Pass2 revisits instructions with those tables available and encodes opcodes, addresses and relocation information into object output. Thus final object generation is assigned to pass2. An implementation could emit some provisional bytes earlier, but that optimization does not change the conventional two-pass division asked here. The answer concerns final object code, not the intermediate source representation.

Original paper, page 4

Report issue

Literal-table insertion pass

Compiler Phases, Linking & Loading

Question 3(ii.b), GATE 1992: In a conventional two-pass assembler, in which pass are literals added to the literal table?
Question 3(ii.b), GATE 1992: In a conventional two-pass assembler, in which pass are literals added to the literal table?
Question 3(ii.b), GATE 1992: In a conventional two-pass assembler, in which pass are literals added to the literal table?
Tap to enlarge
Answer & solution

Answer: Pass1 (no official key was published)

When pass1 encounters a literal operand, it records its value and storage needs in the literal table. Literal-pool directives or the end of a section determine placement, which must be included in layout before addresses are finalized. Pass2 can then use the assigned literal addresses while emitting instructions and literal data. Adding the literals only after computing all addresses would require revising the layout. Thus entry into the table is a first-pass activity, distinct from outputting its bytes.

Original paper, page 4

Report issue

Assembly listing pass

Compiler Phases, Linking & Loading

Question 3(ii.c), GATE 1992: In a conventional two-pass assembler, in which pass is the final listing printed?
Question 3(ii.c), GATE 1992: In a conventional two-pass assembler, in which pass is the final listing printed?
Question 3(ii.c), GATE 1992: In a conventional two-pass assembler, in which pass is the final listing printed?
Tap to enlarge
Answer & solution

Answer: Pass2 (no official key was published)

A useful final assembly listing combines source statements with assigned addresses and generated machine code, plus diagnostics. Since those final encodings are produced in pass2, the conventional listing is printed there as well. Pass1 may produce temporary listings or diagnostics, but that is not the standard final annotated listing meant in this matching task. The answer therefore follows the output artifact’s dependencies rather than assuming any printed text must wait until pass2 in every implementation.

Original paper, page 4

Report issue

Local-symbol address resolution pass

Compiler Phases, Linking & Loading

Question 3(ii.d), GATE 1992: In a conventional two-pass assembler, in which pass are local-symbol addresses established?
Question 3(ii.d), GATE 1992: In a conventional two-pass assembler, in which pass are local-symbol addresses established?
Question 3(ii.d), GATE 1992: In a conventional two-pass assembler, in which pass are local-symbol addresses established?
Tap to enlarge
Answer & solution

Answer: Pass1 for defining addresses; pass2 for substituting them into uses (no official key was published)

Pass1 advances the location counter and associates each defined label with its address, thereby resolving the address values stored in the symbol table. Pass2 looks up those values when encoding references, especially forward references. Hence the standard matching answer is pass1 when “address resolution” means establishing the local symbol’s address. If it instead means replacing a symbolic operand at a use site with that address, the operation is pass2. The two meanings are explicitly distinguished because the printed wording does not name the phase’s exact suboperation.

Original paper, page 4

Descriptive
Report issue

Correct copy-in copy-out implementation

Runtime Environments & Parameter Passing

Question 10(a), GATE 1992: For P(A[i]), where P has an integer formal parameter, a proposed implementation creates local z, sets z:=A[i], runs P’s body using z, then writes A[i]:=z. Identify the parameter-passing mechanism, judge correctness and give a small correction.
Tap to enlarge
Answer & solution

Answer: Call by value-result (copy-in/copy-out); capture the actual argument’s location at call time and copy back to that same location. (no official key was published)

The separate local variable receives the initial value and is copied back on return, so the intended mechanism is call by value-result, also called copy-in/copy-out. It is not call by reference, which uses the actual storage throughout execution, nor call by value, which never copies a final value back. Call by name re-evaluates an actual-argument expression in its caller environment on each use rather than using one private copied value.

The proposed copy-back re-evaluates A[i]. If the caller’s index changes during execution, it can select a different element from the one used at entry. For example initially i=2 and A[2]=10. Suppose the body changes the caller-visible index to 3 through a global reference and leaves the formal’s local value as 99. Re-evaluating A[i] on exit writes A[3]=99 instead of copying back into A[2]. An implementation must preserve the original actual location under the usual location-fixed value-result convention.

Small correction

p:=address_of(A[i]);   {evaluate actual location in caller environment once}
z:=value_at(p);       {copy in}
execute P body with every occurrence of its formal bound to z;
value_at(p):=z;       {copy out to saved location}
If A is known not to change identity or base address, saving k:=i and using A[k] for both transfers is sufficient; saving the address is the general correction. Normal return is assumed, and with one parameter there is no multiple-copy-back ordering issue.

There is also a naming issue in the printed wording: P’s formal is named i, while the actual A[i] contains the caller’s i. They are different bindings. The body must substitute z for the formal, not literally search for the caller expression A[i] in the body. Merely assigning the formal does not itself change the caller’s separate index; the failure requires that the caller-visible index or array location can otherwise change. If that cannot happen, the original sequence happens to produce the right result.

Original paper, page 7

Descriptive
Report issue

Activation records and lexical display

Runtime Environments & Parameter Passing

Question 10(b), GATE 1992: For the following lexically scoped Pascal-like skeleton, draw activation records and the display just after the procedures invoked at labels x and y begin. Distinguish the two A declarations.
program Test;
  procedure A;                 {outer A}
    procedure B;
      procedure A;             {inner A}
      begin ... end;
    begin
      y: A;
    end;
  begin
    B;
  end;
begin
  x: A;
end.
Tap to enlarge
Answer & solution

Answer: At x: Test→A_outer with display [Test,A_outer]. At y: Test→A_outer→B→A_inner with display [Test,A_outer,B,A_inner]. (no official key was published)

Assign lexical levels Test=0, A_outer=1, B=2 and A_inner=3. The declarations, not the dynamic call order, determine these levels. The call x:A in Test resolves to A_outer. The call y:A in B resolves to the nearest enclosing declaration of A, namely B’s own nested A_inner; it does not recursively invoke A_outer.

Immediately after x’s callee starts, before A_outer executes B, the stack and display are:
Stack bottom→top:
[Test frame: caller/runtime link]
[A_outer frame: dynamic link→Test; static link→Test;
return continuation→after x:A; saved previous display[1]]
Display: D[0]→Test, D[1]→A_outer.
D[2] and D[3] have no active corresponding frames and are undefined/unused. Do not invent B or A_inner frames at this first instant.

A_outer then calls B, whose body calls A_inner at y. Immediately after y’s callee starts:

Stack bottom→top:
[Test]
[A_outer: DL→Test, SL→Test, return→after x:A, saved old D[1]]
[B: DL→A_outer, SL→A_outer, return→after B call, saved old D[2]]
[A_inner: DL→B, SL→B, return→after y:A, saved old D[3]]
Display diagram:
D[0] ──> Test
D[1] ──> A_outer
D[2] ──> B
D[3] ──> A_inner

The dynamic link names the calling activation, while the static link names the activation of the lexical parent. They happen to coincide throughout this simple nested call chain; their meanings remain different. A display-based implementation can replace static-chain access entirely, so the static links shown are explanatory rather than required additional storage. On entry at lexical level ℓ, save old D[ℓ] in the frame and set D[ℓ] to that frame; on return restore the saved value. Return addresses, saved registers and local-storage slots are conventional frame fields, but no particular byte sizes or actual locals are specified. The omitted body of A_inner has not yet executed at the requested second snapshot, so no additional calls or frames may be assumed.

Original paper, page 7

Descriptive
Report issue

Type assignment with end-only semantic actions

Semantic Analysis & Type Checking

Question 11(a), GATE 1992: Add syntax-directed semantic rules to the ends of productions, without changing the grammar, so each identifier gets its declared type in the symbol table:
D → T L ;
T → int | real
L → L , id | id
Tap to enlarge
Answer & solution

Answer: Collect identifier-entry references in synthesized L.entries; assign T.type to them at D → T L ;. (no official key was published)

A synthesized list of symbol-table references solves the end-only restriction without needing to pass an inherited type into L before parsing it. Give T a synthesized attribute type and L a synthesized attribute entries. The lexical token id.entry is a reference to that identifier's symbol-table entry (or the declaration entry created for it in the current scope).

Attach precisely these actions at production ends:
D → T L ; { for each p in L.entries: p.type := T.type }
T → int { T.type := integer }
T → real { T.type := real }
L₀ → L₁ , id { L₀.entries := append(L₁.entries, id.entry) }
L → id { L.entries := [id.entry] }

The subscripts distinguish the two occurrences of L; they are attribute notation, not new grammar symbols. append constructs or extends a list of references, not copies of symbol-table records. On reduction of L → id, the one-element list is available. Each reduction of the recursive production adds one further identifier. By induction on the list length, the final L.entries contains exactly the identifiers in this declaration. At the D reduction both T.type and the complete list are available, so every listed entry receives the same type.

For real x,y,z;, T.type becomes real, the L lists successively become [x], [x,y], [x,y,z], and the final action assigns real to x, y, and z. All actions are at the right ends, and the original productions are untouched. Redeclaration detection and nested-scope lookup are separate symbol-table concerns. With a tail pointer or linked-list concatenation, building and processing a k-identifier list costs O(k) time and O(k) references.

Original paper, page 8

Descriptive
Report issue

Eager Boolean expression quadruples

Intermediate Code

Question 11(b), GATE 1992: Generate three-address quadruples in compiler generation order for (a+b) > (c+d) or a > c and b < d. Use usual precedence; partial/short-circuit evaluation is forbidden.
Tap to enlarge
Answer & solution

Answer: Seven quadruples, ending in t7 = t3 or (t4 and t5); all operands are evaluated. (no official key was published)

The parse is ((a+b)>(c+d)) or ((a>c) and (b<d)), because arithmetic binds before comparison and and binds before or. Generate code in a left-to-right postorder traversal, storing each intermediate value in a fresh temporary. A quadruple is (operator, argument1, argument2, result):

1. (+, a, b, t1)
2. (+, c, d, t2)
3. (>, t1, t2, t3)
4. (>, a, c, t4)
5. (<, b, d, t5)
6. (and, t4, t5, t6)
7. (or, t3, t6, t7)

Thus t1=a+b, t2=c+d, and t3 is the first Boolean comparison. Independently t4 and t5 compute both comparisons in the second arm; t6 combines them, and t7 is the final Boolean value. All comparison and Boolean results are represented as Boolean values (or conventional 0/1 encodings), not jump destinations. Every operation executes even if t3 is already true or t4 is false. A jump-based short-circuit sequence would violate the explicit prohibition on partial evaluation.

There are seven internal nodes in the expression tree and one quadruple per node. Temporary names and the order of independent child computations can differ in valid implementations; this is one conventional compiler generation order, not a uniquely mandated register allocation.

Original paper, page 8

2 marks · Other
Not in GATE 2027 syllabusReport issue

Registers with minimum operand-memory traffic

Code Generation & Register Allocation

Question 1(xi), GATE 1991: Evaluate (a+b)*c−d/e**f on a two-address machine whose operands may be registers or memory. Minimize operand memory accesses and give the required registers. ** denotes exponentiation.
Question 1(xi), GATE 1991: Evaluate (a+b)*c−d/e**f on a two-address machine whose operands may be registers or memory. Minimize operand memory accesses and give the required registers. ** denotes exponentiation.
Question 1(xi), GATE 1991: Evaluate (a+b)*c−d/e**f on a two-address machine whose operands may be registers or memory. Minimize operand memory accesses and give the required registers. ** denotes exponentiation.
Tap to enlarge
Answer & solution

Answer: 2 registers and 6 input reads, excluding final result storage (no official key was published)

Assume six independent input values initially reside in memory, arithmetic allows a memory source and register destination, and exponentiation is an available operation. Read e into R1 and compute R1:=R1**f; read d into R2 and compute R2:=R2/R1. Reuse R1 for a, then add b and multiply by c; finish R1:=R1−R2. Each of a, b, c, d, e, f is read once, achieving the six-read lower bound. Two registers retain one partial result while forming the other; one register would require a spill or destructive memory temporary and extra traffic. A required final output store adds one access; instruction fetches are not operand accesses.

Original paper, page 1

2 marks · MSQ
Not in GATE 2027 syllabusReport issue

Link-editor responsibility

Compiler Phases, Linking & Loading

Question 3(ix), GATE 1991: A link editor matches external names to definitions in other modules, macro arguments to parameters, subroutine parameters to arguments, or serves as an editor/compiler user interface?
Question 3(ix), GATE 1991: A link editor matches external names to definitions in other modules, macro arguments to parameters, subroutine parameters to arguments, or serves as an editor/compiler user interface?
Tap to enlarge
Select all that apply
Answer & solution

Answer: B: resolve external names across modules (no official key was published)

Separately compiled modules contain symbol definitions and unresolved references to symbols defined elsewhere. The linker combines modules, locates matching definitions, assigns final locations and adjusts references or relocation records. This is the external-name matching described by B. Macro-parameter substitution belongs to macro expansion, and runtime argument passing or compiler checking handles subroutine parameters. The tool’s name does not mean it is an interactive bridge to a text editor. Dynamic linking can defer some resolution, but the semantic task remains symbol binding across modules.

Original paper, page 4

2 marks · MSQ
Not in GATE 2027 syllabusReport issue

Compiler and language claims

Other / Mixed Topics

Question 3(x), GATE 1991: Assess A recursive descent cannot handle left recursion; B postfix is best for optimization; C without recursion/pointers dynamic allocation is unnecessary; D C can simulate call-by-name; E no Pascal feature violates strong typing.
Question 3(x), GATE 1991: Assess A recursive descent cannot handle left recursion; B postfix is best for optimization; C without recursion/pointers dynamic allocation is unnecessary; D C can simulate call-by-name; E no Pascal feature violates strong typing.
Tap to enlarge
Select all that apply
Answer & solution

Answer: A, D in the conventional parser model; C requires extra language restrictions (no official key was published)

Naive recursive descent expands a left-recursive nonterminal before consuming input and recurses indefinitely, so A is true for that standard algorithm; specialized modern techniques are outside this model. Optimization usually needs explicit dataflow such as three-address code or DAGs, not merely postfix order, so B is false. C is not guaranteed: runtime-sized arrays can require dynamic storage even without pointers or recursive calls. D is achievable with thunks, using a function plus captured environment to reevaluate an argument; writable parameters additionally need an lvalue-access mechanism. Historical Pascal variant records can bypass type discipline, refuting E. C is sometimes intended under a restricted static-allocation language model, but that restriction is not stated.

Original paper, page 4

Descriptive
Report issue

Call by value with an expression argument

Runtime Environments & Parameter Passing

Question 9(a.i), GATE 1991: All variables are integers. Procedure P(a,b,c) executes a:=2; c:=a+b. Main executes x:=1; y:=5; z:=100; P(x,x*y,z); write(x,z). Determine the output for call by value.
Question 9(a.i), GATE 1991: All variables are integers. Procedure P(a,b,c) executes a:=2; c:=a+b. Main executes x:=1; y:=5; z:=100; P(x,x*y,z); write(x,z). Determine the output for call by value.
Tap to enlarge
Answer & solution

Answer: x=1, z=100. (no official key was published)

With call by value, evaluate the actual arguments in the caller before entering P: x yields 1, x*y yields 5, and z yields 100. Allocate independent local formals with values (a,b,c)=(1,5,100).

The assignment a:=2 changes only the local a. Next c:=a+b computes 2+5=7 and places it in the local c. Neither assignment targets the caller’s variables, so after return x remains 1, y remains 5, and z remains 100. The main program prints x=1,z=100.

The intermediate c=7 is not the value printed by the program: the print is outside P and names z. Ordinary call by value has no copy-out stage. Adding copy-out would change the parameter mechanism to value-result, which is a different question. Evaluating the expression x*y once at the call is crucial for distinguishing this case from call by name.

Original paper, page 6

Report issue

Reference parameters and expression actuals

Runtime Environments & Parameter Passing

Question 9(a.ii), GATE 1991: All variables are integers. Procedure P(a,b,c) executes a:=2; c:=a+b. Main executes x:=1; y:=5; z:=100; P(x,x*y,z); write(x,z). Determine the output for call by reference, stating any validity assumption.
Question 9(a.ii), GATE 1991: All variables are integers. Procedure P(a,b,c) executes a:=2; c:=a+b. Main executes x:=1; y:=5; z:=100; P(x,x*y,z); write(x,z). Determine the output for call by reference, stating any validity assumption.
Tap to enlarge
Answer & solution

Answer: Strict reference-only actuals: invalid call, no defined output. If expression actuals are materialized in a temporary: x=2,z=7. (no official key was published)

Pure call by reference binds each formal to an assignable storage location. The actuals x and z have such locations, but x*y is an arithmetic expression and has no variable location to which a conventional reference formal can bind. Thus in a language requiring variable actuals for reference parameters, this call is rejected and there is no output. This is an important qualification to the otherwise familiar textbook calculation.

If the intended pseudo-language permits an expression actual by evaluating it into a temporary, evaluate x*y=1·5=5 at call entry and bind b to that temporary. Bind a directly to x and c directly to z. Executing a:=2 sets x to 2. The temporary b remains 5; it is not a live expression. Then c:=a+b sets z=2+5=7. On return the program prints x=2,z=7.

The temporary convention is sufficient here because P never assigns to b. It is nevertheless an additional semantic rule, not inherent in reference passing. In particular, re-evaluating x*y after changing x would give 10 and would implement call by name rather than this temporary-backed reference convention.

Original paper, page 6

Report issue

Call by name re-evaluates the expression

Runtime Environments & Parameter Passing

Question 9(a.iii), GATE 1991: All variables are integers. Procedure P(a,b,c) executes a:=2; c:=a+b. Main executes x:=1; y:=5; z:=100; P(x,x*y,z); write(x,z). Determine the output for call by name.
Question 9(a.iii), GATE 1991: All variables are integers. Procedure P(a,b,c) executes a:=2; c:=a+b. Main executes x:=1; y:=5; z:=100; P(x,x*y,z); write(x,z). Determine the output for call by name.
Tap to enlarge
Answer & solution

Answer: x=2,z=12. (no official key was published)

Call by name delays evaluation of an actual argument until its formal is used, in the caller’s environment. Think of a as a getter/setter for x, b as a thunk returning x*y, and c as a getter/setter for z. The caller’s x and y, not unrelated locals inside P, are the names captured by b’s thunk.

The first statement a:=2 follows the location associated with x and changes x from 1 to 2. The next statement c:=a+b first obtains a=2 and evaluates b’s expression using the current caller state: x*y=2·5=10. It therefore writes 12 through c into z. After return, main prints x=2,z=12.

A textual substitution illustrates this particular collision-free example: x:=2; z:=x+x*y. General call-by-name implementations must preserve environments and avoid accidental name capture, so literal substitution is only an explanatory model. The difference from temporary-backed reference passing is that b is not frozen at its original value 5. The nonassignability of x*y does not prevent this example’s by-name use because b is only read, never assigned.

Original paper, page 6

Descriptive
Report issue

Lexical scope selects declaration context

Runtime Environments & Parameter Passing

Question 9(b.i), GATE 1991: Global integers a,b; procedure P sets a:=5;b:=10. Procedure Q declares its own local integers a,b and calls P. Main sets global a:=1;b:=2, calls Q, then prints global a,b. Give output under static scope.
Question 9(b.i), GATE 1991: Global integers a,b; procedure P sets a:=5;b:=10. Procedure Q declares its own local integers a,b and calls P. Main sets global a:=1;b:=2, calls Q, then prints global a,b. Give output under static scope.
Tap to enlarge
Answer & solution

Answer: a=5,b=10. (no official key was published)

Under static, or lexical, scope, a nonlocal name is resolved by the source program’s nesting structure. P is declared at global level, alongside Q, rather than inside Q. The closest enclosing declarations for the a and b used in P are therefore the global variables.

Main first assigns those global variables (1,2). Q then creates a fresh activation containing its own local a,b. Although Q calls P, Q’s locals are not lexically enclosing declarations of P. P’s assignments update the globals to (5,10), leaving Q’s locals untouched. Q returns and its activation disappears. Main then prints the global values a=5,b=10.

A useful implementation view is that P’s static link identifies the global environment, independent of which procedure called it. The existence of same-spelled variables in the caller does not change this link. Their uninitialized values are irrelevant because P never reads or writes them under static scoping.

Original paper, page 6

Report issue

Dynamic scope selects the active caller

Runtime Environments & Parameter Passing

Question 9(b.ii), GATE 1991: Global integers a,b; procedure P sets a:=5;b:=10. Procedure Q declares its own local integers a,b and calls P. Main sets global a:=1;b:=2, calls Q, then prints global a,b. Give output under dynamic scope.
Question 9(b.ii), GATE 1991: Global integers a,b; procedure P sets a:=5;b:=10. Procedure Q declares its own local integers a,b and calls P. Main sets global a:=1;b:=2, calls Q, then prints global a,b. Give output under dynamic scope.
Tap to enlarge
Answer & solution

Answer: a=1,b=2. (no official key was published)

Dynamic scope resolves a free name by searching the active call chain from the current activation outward. During P, the chain is P→Q→main/global. P has no local a or b; the nearest active bindings are Q’s local a,b. Hence P’s assignments set Q’s variables to (5,10), rather than modifying the globals.

The globals were initialized to (1,2) by main and are still (1,2) when Q returns. Q’s locals disappear with its activation, and the final print in main uses the globals. The output is a=1,b=2.

No undefined read is caused by Q’s initially uninitialized locals: P overwrites them before they could be read, and the final print occurs after they are out of scope. Dynamic scoping must not be confused with dynamic memory allocation or call-by-reference parameter passing. It is a rule for selecting which binding an identifier denotes; the assignment operation itself is unchanged.

Original paper, page 6

2 marks · Descriptive
Report issue

Expression grammar precedence and ambiguity

Parsing & Syntax Analysis

Question 10(a), GATE 1991: For arithmetic expressions using binary, mathematically nonassociative operators minus and division, the start symbol is E and the grammar is E→E−T | T; T→T/F | F; F→(E) | id. Is it unambiguous? If so state relative precedence; otherwise provide an unambiguous grammar giving division higher precedence.
Question 10(a), GATE 1991: For arithmetic expressions using binary, mathematically nonassociative operators minus and division, the start symbol is E and the grammar is E→E−T | T; T→T/F | F; F→(E) | id. Is it unambiguous? If so state relative precedence; otherwise provide an unambiguous grammar giving division higher precedence.
Tap to enlarge
Answer & solution

Answer: Unambiguous; / has higher precedence than −, and each operator is parsed left-associatively. (no official key was published)

The grammar separates expression levels: E combines terms with minus, while T combines factors with division. Thus id−id/id parses as id−(id/id), never as (id−id)/id. Division has higher precedence than subtraction.

Both recursive productions are left-recursive, so unparenthesized chains group to the left. For example id−id−id has structure (id−id)−id, and id/id/id has structure (id/id)/id. This is a syntactic associativity convention; it does not claim the arithmetic operators obey an associative law.

For uniqueness, consider an expression outside its matched parentheses. If it has a top-level minus, the root must be E→E−T, split at its last such minus because T cannot contain an unparenthesized minus. If there is no such minus, use E→T. Similarly a top-level slash in a term forces T→T/F split at its last top-level slash, since F cannot contain an unparenthesized slash. At the factor level, either the token is id or the uniquely matched outer parentheses contain an expression, to which the same argument applies. Induction on expression length gives a unique parse. Redundant parentheses are allowed by the grammar, but do not create two parses for the same token string.

Original paper, page 7

4 marks · Descriptive
Report issue

Generate only necessary expression parentheses

Parsing & Syntax Analysis

Question 10(b), GATE 1991: For arithmetic expressions using binary, mathematically nonassociative operators minus and division, the start symbol is E and the grammar is E→E−T | T; T→T/F | F; F→(E) | id. Does it permit redundant parentheses such as (id/id) and id−(id/id)? Modify it to eliminate redundant parentheses, making minimal changes and adding at most one production rule.
Question 10(b), GATE 1991: For arithmetic expressions using binary, mathematically nonassociative operators minus and division, the start symbol is E and the grammar is E→E−T | T; T→T/F | F; F→(E) | id. Does it permit redundant parentheses such as (id/id) and id−(id/id)? Modify it to eliminate redundant parentheses, making minimal changes and adding at most one production rule.
Tap to enlarge
Answer & solution

Answer: Yes. E→T|S; S→E−T|E−(S); T→id|T/F|(S)/F; F→id|(S)|(T/F)|((S)/F). Only the production group S is added. (no official key was published)

The original grammar allows both examples through F→(E). Deleting parentheses must be judged by preservation of the parse tree under / precedence and left associativity, not accidental numerical identities for particular values. Parentheses are needed around a subtraction in either operand of division, around a division in the right operand of division, and around a subtraction in the right operand of subtraction. They are not needed around a whole expression, a single id, a left operand at equal precedence, or a division used as a subtraction operand.

Use the following four-nonterminal grammar:
E→T | S
S→E−T | E−(S)
T→id | T/F | (S)/F
F→id | (S) | (T/F) | ((S)/F)

S is exactly subtraction-rooted, while T/F and (S)/F together are exactly division-rooted. This grammar generates every binary expression tree with no removable parenthesis pair. F appears only after /, preventing redundant outer parentheses. Examples: it generates id−(id−(id−id)) and id/((id−id)/id), but rejects (id/id), id−(id/id), (id), and ((id−id))/id. The source’s “one more production rule” is interpreted in the common sense of one more nonterminal production group: only S is added to E,T,F. All three original groups must change to prevent the old whole-expression wrapping while preserving needed contexts. A global minimum in number of RHS alternatives is not claimed because the source does not define its edit metric.

Original paper, page 7

4 marks · Descriptive
Report issue

Eliminate direct and indirect left recursion

Parsing & Syntax Analysis

Question 10(c), GATE 1991: For arithmetic expressions using binary, mathematically nonassociative operators minus and division, the start symbol is E and the grammar is E→E−T | T; T→T/F | F; F→(E) | id. Part (b) requires necessary-parentheses-only expressions. For the grammar E→T|S; S→E−T|E−(S); T→id|T/F|(S)/F; F→id|(S)|(T/F)|((S)/F), remove left recursion.
Question 10(c), GATE 1991: For arithmetic expressions using binary, mathematically nonassociative operators minus and division, the start symbol is E and the grammar is E→E−T | T; T→T/F | F; F→(E) | id. Part (b) requires necessary-parentheses-only expressions. For the grammar E→T|S; S→E−T|E−(S); T→id|T/F|(S)/F; F→id|(S)|(T/F)|((S)/F), remove left recursion.
Question 10(c), GATE 1991: For arithmetic expressions using binary, mathematically nonassociative operators minus and division, the start symbol is E and the grammar is E→E−T | T; T→T/F | F; F→(E) | id. Part (b) requires necessary-parentheses-only expressions. For the grammar E→T|S; S→E−T|E−(S); T→id|T/F|(S)/F; F→id|(S)|(T/F)|((S)/F), remove left recursion.
Tap to enlarge
Answer & solution

Answer: E→TR; R→−TR|−(S)R|ε; S→T−TR|T−(S)R; T→idU|(S)/FU; U→/FU|ε; F→id|(S)|(T/F)|((S)/F). (no official key was published)

First notice the indirect cycle E→S→E−T or E−(S). Removing only the obvious T→T/F recursion is insufficient. Substitute S’s alternatives into E to obtain E→T | E−T | E−(S). Its recursive suffixes are −T and −(S); its base is T. Introduce a tail R:
E→T R
R→−T R | −(S) R | ε.

S must still mean a subtraction-rooted expression, not an arbitrary E. Substituting E=T R into S initially gives S→T R−T | T R−(S). This is valid, but an equivalent clearer form selects the first subtraction and then any remaining subtraction tail:
S→T−T R | T−(S) R.
Both describe a T followed by a nonempty sequence of subtraction suffixes. Their ordering is preserved; the rewrite is about syntax, not commuting arithmetic operations.

Remove T’s immediate recursion T→T/F | id | (S)/F using a new tail U:
T→id U | (S)/F U
U→/F U | ε.
Keep F→id | (S) | (T/F) | ((S)/F).

The complete grammar is the six displayed groups E,R,S,T,U,F. Every nonempty derivation of T begins with id or “(”. E and S begin through T; F directly begins with id or “(”; R begins with “−” or ε, and U with “/” or ε. No nonterminal can derive itself as the leftmost symbol, so neither direct nor indirect left recursion remains. The language is unchanged by the standard tail transformation. When constructing semantic actions, fold each R or U sequence leftward to retain the original left-associative parse: right-recursive grammar tails must not accidentally change subtraction or division evaluation order. The at-most-one-extra-production restriction belongs to part (b); part (c) requires the additional tail nonterminals.

Original paper, page 7