Go Down

Topic: Doubt about IF statement [SOLVED] (Read 332 times) previous topic - next topic

blastboot

May 13, 2013, 11:40 pm Last Edit: May 14, 2013, 01:23 am by blastboot Reason: 1
Is there any difference between
Code: [Select]
if (main condition) {
if (1st condition) {
do something...
} else if (2nd condition) {
do something...
}
}

and this:
Code: [Select]
if (main condition) {
if (1st condition) {
do something...
}
if (2nd condition) {
do something...
}
}

between using only if's or if and if else's..

Thanks in adance!

Arrch

Yes. The 2nd do something will be run for 1st condition and 2nd condition being true for the second example, but not for the first.

blastboot

Sorry but i couldn't understand

guix

#3
May 14, 2013, 01:01 am Last Edit: May 14, 2013, 01:03 am by guix Reason: 1
Yes there is a difference, it depend what you want to do.

In the first case, the "else if" will be checked only if the first "if" condition wasn't true. In the second case, both conditions will be checked.

So for example in this case:
Code: [Select]

if ( a == 2 )
 // do something

if ( a == 3 )
 // do something else

it is better to use a "else if".


But in this case for example:
Code: [Select]

if ( a == 2 )
 // do something

if ( b == true )
 // do something unrelated to the first condition

Using a "else if" here, will not be what you want the program to do

blastboot

i got it! many thanks for your help!

Cheers

Go Up