Machine-translated by Google. Questions are authored in English.
Top

Discussion

A student wrote two context-free grammars G1 and G2 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 \(D\) as the start symbol, and use six terminal symbols int ; id [ ] num.

Grammar G1Grammar G2
D → int L;D → int L;
L → id [EL → id E
E → num]E → E[num]
E → num] [EE → [num]

Which of the grammars correctly generate the declaration mentioned above?

  • A.Both G1 and G2
  • B.Only G1
  • C.Only G2
  • D.Neither G1 nor G2

Answer: A

Both G1 and G2 generate the declaration correctly.

G1 derives int a[10][3]; as D ⇒ int L; ⇒ int id [E; then E ⇒ num] [E ⇒ num] [num], giving int id [num] [num];. The rule E → num] ends the dimensions and E → num] [E adds another, so it generates one or more dimensions.

G2 derives it as D ⇒ int L; ⇒ int id E; with E ⇒ E[num] ⇒ [num][num]. E → [num] is one dimension and the left-recursive E → E[num] appends more, again at least one.

Both grammars produce exactly the declarations with one or more bracketed sizes, so the options claiming only one, or neither, are wrong.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.