Reputation: 5508
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()
Upvotes: 1
Views: 23560
Reputation: 745
Following your same example if we use sequence of if
conditions, whatever the input is it will run all 3 conditions. Replacing sequence of if
with if-else
conditions will run only first condition in best case whereas all 3 in worst case.
So conclude with that if-else
will save our running time in most cases, therefore using if-else
is preferred over using sequence of if
conditions.
input = getInputFromUser()
if input is "Hello"
greet()
if input is "Bye"
sayGoodbye()
if input is "Hey"
sayHi()
Upvotes: 0
Reputation: 12187
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...
Upvotes: 13
Reputation: 180944
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.
Upvotes: 13
Reputation: 12413
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.
Upvotes: 7
Reputation: 6580
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.
Upvotes: 8