What is the difference between if and else if

closed account (EwCjE3v7)
Hi there I was just wondering if some one could answer this question
What is the difference between if and else if
if this->object->state1...
elseif this->object->state2...
else puts("This state makes no sense")


What are you confused about?
closed account (EwCjE3v7)
Well you can just do
if () {}
if () {}
if () {}
if () {}

and

if () {}
else if () {}
else if () {}
else if () {}
else if () {}

whats the difference
else blocks execute only if the preceeding if block did not execute.

1
2
3
4
5
6
7
8
if( foo )
{
    // this executes only if foo is true
}
else
{
    // this executes only if foo is false
}


putting another 'if' after the else is like putting it inside the else block:

1
2
3
4
5
6
7
8
9
10
if( foo ) { ... }
else if( bar ) { ... }

// is conceptually the same as

if( foo ) { ... }
else
{
    if( bar ) { ... }
}


As such, chaining together multiple else-if's makes it so that each block is dependent on all previous conditions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if( foo )
{
    // executes only if foo is true
}
else if( bar )
{
    // executes only if foo is false and bar is true
}
else if( baz )
{
    // executes only if foo is false, bar is false, and baz is true
}
else
{
    // executes only if foo, bar, and baz are all false
}



Independent if statements do not depend on previous if statements:

1
2
3
4
5
6
7
8
if( foo )
{
     // executes only if foo is true
}
if( bar ) // <- no else
{
     // executes only if bar is true.  Whether foo was true or not does not matter
}
closed account (EwCjE3v7)
Thanks i got it now. Thanks Dich and congrats on the 10000 thats like the most number of digits anyones got,ur goal now is 100000 :D
Topic archived. No new replies allowed.