cdangling-else

Dangling else query (or an excercise in reading bad code)


The book I'm reading (C How to Program with an into to C++ Global Edition, Deitel&Dietel, 2016) gives the following code: Note that this is how the book presents the code in the exercise section, without braces and indentation on purpose. I would assume to teach you that using correct indentation makes reading code a lot easier.

int main(){
int x = 9, y = 11;
if (x < 10) 
if (y > 10)
puts("*****");
else
puts("#####");
puts("$$$$$");
}

The output is

*****
$$$$$

The book states the compiler always associates an else with the previous if unless told to do otherwise by the placement of braces so by that logic the else is associated with

if (y > 10) 

which is true and the else shouldn't execute, giving an output of

***** 

and not

*****
$$$$$

So my question is why is the line

$$$$$

in the output?


Solution

  • [too long for a comment]

    Even without braces it is quite clear what goes where if indented and new-lined properly (which can be automated, BTW):

    int main() {
      int x = 9, y = 11;
    
      if (x < 10) 
        if (y > 10)
          puts("*****");
        else
          puts("#####");
    
      puts("$$$$$");
    }