Pages: [1]   Go Down
Author Topic: Doubt about IF statement [SOLVED]  (Read 273 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Full Member
***
Karma: 0
Posts: 106
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Is there any difference between
Code:
if (main condition) {
if (1st condition) {
do something...
} else if (2nd condition) {
do something...
}
}
and this:
Code:
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!
« Last Edit: May 13, 2013, 06:23:30 pm by blastboot » Logged

California
Offline Offline
Faraday Member
**
Karma: 88
Posts: 3360
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Offline Offline
Full Member
***
Karma: 0
Posts: 106
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Sorry but i couldn't understand
Logged

France
Offline Offline
God Member
*****
Karma: 34
Posts: 987
Scientia potentia est.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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:
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
« Last Edit: May 13, 2013, 06:03:19 pm by guix » Logged

Offline Offline
Full Member
***
Karma: 0
Posts: 106
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

i got it! many thanks for your help!

Cheers
Logged

Pages: [1]   Go Up
Jump to: