In: Computer Science
Show that the following attempt to solve the dangling else ambiguity is still ambiguous.
statement → if ( exp ) statement |
matched-stmt
matched-stmt → if ( exp ) matched-stmt
else statement | other
exp → 0 | 1
Solution
Consider the following string
if ( 0 ) if ( 0 ) other else if ( 0 ) other else other
We can show two possible leftmost derivations for this, demonstrating the grammar’s ambiguity
Derivation 1
statement -> if (exp) statement
-> if (0) statement
-> if (0) matched-stmt
-> if (0) if (exp) matched-stmt else statement
-> if (0) if (0) matched-stmt else statement
-> If (0) if (0) other else statement
-> if (0) if (0) other else matched-stmt
-> if (0) if (0) other else if (exp) matched-stmt else statement
-> if (0) if (0) other else if (0) matched-stmt else statement
-> if (0) if (0) other else if (0) other else statement
-> if (0) if (0) other else if (0) other else matched-stmt
-> if (0) if (0) other else if (0) other else other
Derivation 2
statement ->matched-stmt
->if (exp) matched-stmt else statement
->if (0) matched-stmt else statement
->if (0) if (exp) matched-stmt else statement else statement
->if (0) if (0) matched-stmt else statement else statement
->if (0) if (0) other else statement else statement
->if (0) if (0) other else if (exp) statement else statement
->if (0) if (0) other else if (0) statement else statement
->if (0) if (0) other else if (0) matched-stmt else statement
->if (0) if (0) other else if (0) other else statement
->if (0) if (0) other else if (0) other else matched-stmt
->if (0) if (0) other else if (0) other else other
---
i wrote the solution in word
after pasted here, format and alignment changed, really sorry for that
all the best