Open In App

Dangling-else Ambiguity

Last Updated : 27 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Compilers and interpreters use grammar to build the data structure in order to process the programs. So ideally one program should have one derivation tree. A parse tree or a derivation tree is a graphical representation that shows how strings of the grammar are derived using production rules. But there exist some strings which are ambiguous. 

A grammar is said to be ambiguous if there exists more than one leftmost derivation or more than one rightmost derivation or more than one parse tree for an input string. An ambiguous grammar or string can have multiple meanings. Ambiguity is often treated as a grammar bug, in programming languages, this is mostly unintended. 

Dangling-else ambiguity

The dangling else problem in syntactic ambiguity. It occurs when we use nested if. When there are multiple “if” statements, the “else” part doesn’t get a clear view with which “if ” it should combine. 

For example:

if (condition) {
}
if (condition 1) {
}
 if (condition 2) {
}
   else
   {
       }

In the above example, there are multiple “ifs” with multiple conditions and here we want to pair the outermost if with the else part. But the else part doesn’t get a clear view with which “if” condition it should pair. This leads to inappropriate results in programming. 

The Problem of Dangling-else:

Dangling else can lead to serious problems. It can lead to wrong interpretations by the compiler and ultimately lead to wrong results. 

For example:

Initialize k=0 and o=0
if(ch>=3) 
if(ch<=10) 
k++;
else
o++;

In this case, we don’t know when the variable “o” will get incremented. Either the first “if” condition might not get satisfied or the second “if” condition might not get satisfied. Even the first “if” condition gets satisfied, the second “if” condition might fail which can lead to the execution of the “else” part. Thus it leads to wrong results. 

To solve the issue the programming languages like C, C++, Java combine the “else” part with the innermost “if” statement. But sometimes we want the outermost “if” statement to get combined with the “else” part. 

Resolving Dangling-else Problem

The first way is to design non-ambiguous programming languages. 

Secondly, we can resolve the dangling-else problems in programming languages by using braces and indentation. 

For example:

if (condition) {
     if (condition 1) {
          if (condition 2) {}
}
}
 else {
 }

In the above example, we are using braces and indentation so as to avoid confusion. 

Third, we can also use the “if – else if – else” format so as to specifically indicate which “else” belongs to which “if”

For example:

if(condition) {
}
else if(condition-1) {
}
else if(condition-2){
}
else{
}

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads