tags:

views:

894

answers:

5

Why would you use if-else statements if you can make another if statement?

Example with multiple ifs:

input = getInputFromUser()
if input is "Hello"
    greet()

if input is "Bye"
    sayGoodbye()

if input is "Hey"
    sayHi()

Example with else-if:

input = getInputFromUser()
if input is "Hello"
    greet()

else if input is "Bye"
    sayGoodbye()

else if input is "Hey"
    sayHi()
+10  A: 

Argh, you need to take cs 101 immediately! learn about branching here

And here is the free online video course from Standford: Introduction to Computer Science

vehomzzz
+6  A: 

you mean like this:

if (a == true && b == false && c == 1 && d == 0) {
    // run if true
}

if (a == false || b == true || c != 1 || d != 0) {
    // else
}

An else-statement would be much clearer and easier to maintain.

Brad Cupit
Chris Lutz
Finally, you ask the processor to do the same work twice.
Tom Leys
@Chris Lutz, found the mistake and fixed it around the same time as you :-)
Brad Cupit
+1  A: 

If you need to chose exactly one action from given set of actions, depending on some conditions, the natural and most clear choice is either switch (don't forget to break after each branch) or combination of if and else. When I write

if (conditon1)
{
    action1();
}
else if (condition2) 
{
    action2();
}
else if (conditon3)
{
    action3();
}
.
.
.
else {
    action_n();
}

it is clear to the reader that exactly one of actions is to be performed. And there is no possibility that because of mistake in conditions more than one action is performed.

Tadeusz Kopec
+4  A: 

It's also more performant.

In your first example, every if will be checked, even if input is "Hello". So you have all three checks.

In your second example, execution will stop once it found a branch, so if the user types "Hello" it will be only one check instead of three.

The difference may not be much in your simple example, but imagine that you're executing a potentially expensive function and you might see the difference.

Michael Stum
+5  A: 

If you have non-exclusive conditions:

if(a < 100)
{...}
else if (a < 200)
{...}
else if (a < 300)
....

this is very different from the same code without the "else"s...

Brian Postow