-1

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?

PerfectContrast
  • 144
  • 2
  • 2
  • 14
  • 1
    "*... and the else shouldn't execute?*" And it does not execute. So all is fine, isn't it? – alk Jan 05 '18 at 16:13
  • Well without the braces I read it as both lines under the else are part of it. – PerfectContrast Jan 05 '18 at 16:26
  • I presume that the lack of indentation is deliberate? Either way, it gets downvote etc. – Martin James Jan 05 '18 at 17:52
  • 2
    @ Yes. as I said the book presents it exactly like this on purpose. I don't see a down vote being applicable here. – PerfectContrast Jan 05 '18 at 17:54
  • There is a persistent set of SO users that subscribe to the view that explaining bad code is somehow useful to future SO users/vistors. I don't belong in that set:) – Martin James Jan 05 '18 at 18:07
  • 3
    @MartinJames It's not bad code. It was void of indents and brackets on purpose to make that particular set of exercises more challenging in the book. The indentation threw me off and a user helped me out. Maybe when someone else reads this book and comes to this exercise they will Google, find this question and their answer. – PerfectContrast Jan 05 '18 at 18:30

2 Answers2

4

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.

user2736738
  • 30,591
  • 5
  • 42
  • 56
4

[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("$$$$$");
}
alk
  • 69,737
  • 10
  • 105
  • 255