Why use if-else if in C ++?

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

An example with several 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()
+1
source share
4 answers

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 "else" s ...

+14
source

It is also more effective.

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

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

, , , .

+13

:

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

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

else .

+8

, , - ( ), if else.

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

, . , - .

+7

All Articles