Question

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 ?

Was it helpful?

Solution

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();
        }
    }
}

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top