Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do different languages handle the "dangling else"?

I often see the dangling else handled as:

if (x > 0)
  if (y > 0)
    print "hello"
else
  print "world"

the parser or interpreter will actually match the else with the closest if statement, which is the "if (y > 0)".

Does any language have the pitfall of actually matching the else with the outer if or the farthest if? (except the obvious Python)

like image 395
nonopolarity Avatar asked Jun 08 '09 23:06

nonopolarity


3 Answers

Short of using space-sensitive languages (like Python, as you said), I don't see why any sensible interpretation would match the outermost if block.

Some languages prohibit this potential ambiguity by:

  1. Requiring braces for all blocks, and
  2. Providing special "else if" syntax, usually elsif, elif, or elseif.
like image 55
Chris Jester-Young Avatar answered Sep 21 '22 23:09

Chris Jester-Young


If any language did that (except for the indentation-centric languages), they would have to go into one of the "what is the worst language" lists.

This is also why I almost always use braces for conditionals, and 100% of the time when there are nested conditionals or loops. The few extra characters is worth eliminating the possibility of confusion.

like image 39
Gerald Avatar answered Sep 18 '22 23:09

Gerald


In Perl, braces are not optional which helps us avoid such issues:

if ($x > 0) {
    if ($y > 0) {
        print "hello"
    }
    else {
        print "world"
    }
}

versus

if ($x > 0) {
    if ($y > 0) {
        print "hello"
    }
}
else {
    print "world"
}

IIRC, most C style guidelines require/recommend braces for loops and conditionals.

like image 24
Sinan Ünür Avatar answered Sep 20 '22 23:09

Sinan Ünür