Question
A student wrote two context-free grammars and for generating a single C-like array declaration. The dimension of the array is at least one. For example,
int a[10][3];
The grammars use as the start symbol, and use six terminal symbols int ; id [ ] num.
Grammar :
Grammar :
Which of the grammars correctly generate the declaration mentioned above?
Official answer and solution
- Official answer
- A
- From
- Official GATE 2016 answer key
Solution
Trace the derivations of and for generating multidimensional array declarations.
A C-like array declaration of dimension has the form:
Trace Grammar :
- For dimension :
- For dimension :
By applying recursively times followed by , generates an array declaration with any dimension . Hence, correctly generates the declaration.
Trace Grammar :
- For dimension :
- For dimension :
By applying the left-recursive rule repeatedly times followed by , generates an array declaration with any dimension . Hence, correctly generates the declaration.
Therefore, both and correctly generate the declaration.
A
Assuming is invalid because the opening bracket is in the production for rather than , overlooking that the brackets match up identically in the full string.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2016 Computer Science and Information Technology (CS) Session 2
- Question
- 56 of 65, printed as CS Q.46
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.