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)
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:
elsif
, elif
, or elseif
.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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With