-2

I was wondering if there's any difference between these two codes:

Code 1:

if(isSleepy()){
    sleep(1);
} else if (isBored()){
    dance();
    dance();
} else {
    walkRight(50);
    walkLeft(50);
    if(isHungry()){
        eat();
    }
}

Code 2:

if(isSleepy()){
    sleep(1);
}
if (isBored()){
    dance();
    dance();
}
walkRight(50);
walkLeft(50);
if(isHungry()){
    eat();
}

I've replaced the if-elseif-if chain with if only. Does that affect the conditionnal process ?

Dreadlockyx
  • 181
  • 1
  • 11
  • 1
    Have you tried to run it and see what happens? – default locale Sep 29 '13 at 15:59
  • Yes. Since the boolean tired is false it would do `dance()` twice anyway in the fist case. After having danced twice, `eat()` was not called, so that's why I came here to understand the conditional process. – Dreadlockyx Sep 29 '13 at 16:22

3 Answers3

3

Does that affect the conditionnal process ?

Yes, it does. In the first case, isBored() is never called nor its result checked if isSleepy() returns true. In the second case, it is checked, it's completely independent. Similarly, walkRight and walkLeft won't be called in the first block if isSleepy() returns true, but they will be in the second block.

This reformatting of the first code block may help make things more clear;

if(isSleepy()){
    sleep(1);
} else {
    // The below only happens if isSleepy() returned false
    if (isBored()){
        dance();
        dance();
    } else {
        // These only happen if isSleepy() returned false AND isBored() returned false
        walkRight(50);
        walkLeft(50);
        if(isHungry()){
            eat();
        }
    }
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

else if is checked only in case when preceding if condition fails. Simple if one after the other will be executed and evaluated no matter what happened to preceeding if statement.

To understand simply translate if-else meaning

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

In first case, else block is never checked if else if condition is true which itself is never checked if if condition is true.

In second case, both if conditions are checked and the third block isn't inside any condition, it is always executed.

Does that affect the conditionnal process ?

In first code, the conditions are mutually exclusive but in second code both conditions may be true at the same time.

TheKojuEffect
  • 20,103
  • 19
  • 89
  • 125