Dangling Else

  • Given the un-indented code, which if gets to claim the else?
  • 
                if x > 3
                if y > 3 print(a)
                else print b
                
    
                if x > 3
                  if y > 3 print(a)
                  else print b
                
    
                if x > 3
                  if y > 3 print(a)
                else print b
                
    Closest unmatched if The other solution
    x = 1, y = 1 nothing b
    x = 1, y = 5 nothing b
    x = 5, y = 1 b nothing
    x = 5, y = 5 a b

Dangling Else

To avoid dangling else woes
  • Insist on { } always (Swift) <-- NOT Java, C, C++
  • Add an endif word (Bash)
  • Insist on indentation (Python)
  • Insist on else always (Haskell)