Fixing the “dangling else”

The solution to this dilemma is quite pragmatic – use an explicit terminator for all control structures. For example the statement in the previous post becomes (in Algol 68):

if expr1 then 
    if expr2 then 
        S1
    fi 
else 
    S2 
fi

A sequence of statements is allowed between the keywords then and else, and between else and fi. This makes it unnecessary to use the delimiters  begin and end  to construct a compound statement. Note in early coding, it was not uncommon to express the above in the following format:

if expr1 then if expr2 then S1 fi else S2 fi

A similar solution was proposed by Ada, using the keyword end if. But instead of fixing this nightmare – we leave it in. This starts to become complicated (and messy) with an increase in nesting. For example:

if expr1 then
   S1
else if expr2 then
   S2
else if expr3 then
   S3
else
   S4
end
end
end

So languages that use end-markers often provide a keyword such as elsif, elseif or elif. The above code then becomes:

if expr1 then
   S1
elsif expr2 then
   S2
elsif expr3 then
   S3
else
   S4
end

For those programming in a language that doesn’t offer control-structure terminators, such as C? Use explicit  { } to properly terminate each if-else pair. For example:

if (expr1) {
    if (expr2) { 
        S1
    } 
}
else 
    S2 

 

 

 

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