What’s with the “dangling” else?

One of the problems novice programmers are faced with is syntactic ambiguities such as the dangling-else problem, sometimes known as the hanging else. Dangling-else really just means that an optional else clause in a nested conditional structure becomes ambiguous. The original of the dangling else dates back to the design of the language ALGOL 60 which introduced the notion of two forms of the conditional if statement:

if expr then S1
if expr then S1 else S2

This was an unfortunate sequence of events, because it gave rise to inherent ambiguities in the code when nested statements were used. Consider the following piece of code:

if expr1 then if expr2 then S1 else S2

This can be interpreted one of two ways:

if expr1 then (if expr2 then S1 else S2)

OR

if expr1 then (if expr2 then S1) else S2

Or course the compiler will interpret it the way it was designed to, which may or may not gel with how the algorithm has been designed. We associate the dangling else predominantly with C, however it exists in other languages. Pascal for example had a similar issue. Java, C++, all seem to be afflicted. Many of the languages that avoided the dangling-else, did so with the use of explicit end markers.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s