How do different languages handle the "dangling else"?
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:
- Requiring braces for all blocks, and
- Providing special "else if" syntax, usually
elsif
,elif
, orelseif
.
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.