Is there a difference between several if statements, and if?

If i write

int a = 1;
int b = 2;

if (a == b) {

//Do something

} else if (a > b) {

//Do something else

} else if (a < b) {

//Do something else

}

Unlike:

if (a == b) {

//Do something

}
if (a > b) {

//Do something else

}
if (a < b) {

//Do something else

}

Is there any difference in how the compiler interprets code or speed? I see no logical difference, but there must be a reason why there is an if else statement. This is just the difference in breaking the line.

+4
source share
4 answers

In the above scenario, they are the same except for speed. If/ elsewill be faster than the Ifs series , since instructions are elseskipped if the condition is met If. On the other hand, in the Ifs series, each condition is evaluated separately.

, , , If/else If . :

// this:
if(x <= 0) {
    x = 1;
}
else { // only true if x started out > 0
    x = 37;
}

// is different from this:
if(x <= 0) {
    x = 1;
}
if(x > 0) { // always true in this version
    x = 37;
}
+6

else-if, , else-if .

if .

, , a=b.

:

int a = 1;
int b = 1;
if (a == b) 
{
    //Do something
} 
else if (a > b) 
{
    //Do something else
} 
else if (a < b) 
{
    //Do something else
}

, a=b, (a>b a<b).

  • , a=b.

  • .

  • .

:

int a = 1;
int b = 1;
if (a == b) 
{
     //Do something
}
if (a > b) 
{
    //Do something else
}
if (a < b) 
{
    //Do something else
}

, .

  • , a=b.

  • .

  • , a>b.

  • , a<b.

+6

. put . Else .

0
source

the time complexity of if-else statements is less than if statements. Therefore if-else steements are very beneficial

-1
source

Source: https://habr.com/ru/post/1529524/


All Articles