In: Computer Science
Describe how each of Algol 60, Pascal, and Pytho 3 handles the dangling else problem.
Dangling else problem arise when this kind of statements occur in the program:
if b1 then
if b2 then
S1
else
S2
Above b1, b2 are conditions whereas S1 and S2 are statements.
What is the problem in the above statement?
Problem is that if b1 holds true but if b2 holds false then
compiler got confused with
the subsequent else statement whether it is associated with first
if that is having b1
condition or it is associated with second if that is b2 having
condition.
Solution in Algol 60:
Algol 60 solve the problem of dangling else by restricting the
use of if immediately after
then that is in our example after first if having b1 as condition
another if is not allowed
in algol 60 having b2 as condition to solve this problem.
Solution in Pascal:
In pascal a different strategy is followed to solve the dangling
else problem, here the ambiguous
else part is associated with innermost if that is in the example we
considered else part is
associated with if having b2 condition.
Solution in python3:
In python 3 dangling else problem is solved by using indentation. Example
if b1:
if b2:
S1
else:
S2
Above else is assocaited with the if having b2 as condition because
else is indented with this if.
But if the statement are written this way:
if b1:
if b2:
S1
else:
S2
Here the else will be associated with the if having b1 as
condition because it is indented with this
if.