Differentiate between Ambiguous and Unambiguous Grammar


Before understanding the differences between ambiguous grammar and unambiguous grammar, let us learn about these concepts.

Ambiguous Grammar

A grammar is said to be ambiguous if there exists more than one left most derivation or more than one right most derivation or more than one parse tree for a given input string.

  • If the grammar is not ambiguous then we call unambiguous grammar

  • If the grammar has ambiguity then it is good for compiler construction

  • No method can automatically detect and remove the ambiguity, but we can remove the ambiguity by re-writing the whole grammar without ambiguity.

Example

Let us consider a grammar with production rules −

E=I
E=E+E
E=E*E
E=(E)
E= ε|0|1|2|3……9

Unambiguous Grammar

A grammar can be unambiguous if the grammar does not contain ambiguity that means if it does not contain more than one left most derivation or more than one right most derivation or more than one parse tree for the given input string.

Example

S -> AB
A -> Aa / a
B -> b

Differences

The major differences between ambiguous and unambiguous grammar are as follows −

Ambiguous GrammarUnambiguous Grammar
It generates more than one- parse tree ( syntax tree or derivation tree)It generates exactly one- parse tree (derivation tree or syntax tree)
In this type of grammar, the leftmost and rightmost derivation represents different parse trees.In this type of grammar, leftmost and rightmost derivations represent the same parse tree.
This grammar contains a smaller number of non-terminals.This grammar contains a greater number of non-terminals.
The length of the parse tree is less.The length of the parse tree is large.
Example 
S → S + S / S x S / id
(Ambiguous Grammar)
Example 
S → S + E / E
E → E x F / F
F → id
(Unambiguous Grammar)

Updated on: 15-Jun-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements