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

98 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

[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("$$$$$");
}
0
On

You wrote this (equivalent to yours)

if (x < 10) { 
   if (y > 10) {  
      puts("*****");
   }else{
      puts("#####");
   }
}
puts("$$$$$");

And it is following what you said. The else matches with the closest if. Here y>10. And the if and else always consider the single statement when we don't use brackets. Here if-else block inside the outer if serves the purpose of the single statement. Same way the for the else the single puts("####") serves the purpose. The last puts will be executed no matter what the value of x and y be.