smilingbuddha
smilingbuddha

Reputation: 14660

Usage of if, else, and else if

What is the difference between:

if      (expr1) {stmt}
else if (expr2) {stmt}
else if (expr3) {stmt}    
else            {stmt}

And the same code block written as:

if (expr1) {stmt}
if (expr2) {stmt}
if (expr3) {stmt}    
else       {stmt}

Upvotes: 3

Views: 920

Answers (7)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

With:

if      (expr1) {stmt1}
else if (expr2) {stmt2}
else if (expr3) {stmt3}    
else            {stmt4}

One and only one of the statements can be executed.


With:

if (expr1) {stmt}

if (expr2) {stmt}

if (expr3) {stmt}    
else       {stmt}

Either, both, or none of the first and second sections will be executed. In the last if-else section, either stmt3 or stmt4 will be executed.

Upvotes: 0

Brendan Long
Brendan Long

Reputation: 54242

Here's another good example to see how this works.

This example will print "FirstSecond":

if(1) {
    printf("First");
}
if(1) {
    print("Second");
}

This just prints "First":

if(1) {
    printf("First");
}
else if(1) {
    print("Second");
}

Upvotes: 1

NiematojakTomasz
NiematojakTomasz

Reputation: 2473

For example if condition1 == true and condition2 == true the first block(else id) will execute only some statements#1 and the second block would execute both some statements#1 and some statements#2. When you use else if the program would stop matching next conditions after first matched. It would be slightly faster on runtime if conditions are exclusive(i'm not sure if it's right word).

Upvotes: 0

Max
Max

Reputation: 1068

For the best performance choose a if else (if possible).

You can also use a switch case statement.

Upvotes: 0

flight
flight

Reputation: 7272

In the first case exactly one of the blocks will be executed. In the second, the first and second blocks may or may not be executed and exactly one of the last two blocks will be executed.

Upvotes: 0

robert
robert

Reputation: 3615

In your first code, at most ONE of the blocks can be executed.

In the second code, all of the blocks could be executed. (Except for the last else-thing.)

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

In the first one, each block of statements is mutually exclusive; the structure guarantees that exactly one of them will get executed.

This is not true for the second one. Consider:

if (a == 2) { /* blah */ }
if (a == 3) { /* blah */ }
if (a < 5)  { /* blah */ }

If a == 2, then two of the blocks will get executed.

Upvotes: 10

Related Questions