Question regarding "else if"

  • Thread starter Thread starter JollyK
  • Start date Start date
J

JollyK

Hello folks, So what is the difference between

Code:
if (a == b) {...}
if (c==d) {...}
if (e==f) {...}

and

Code:
if (a == b) {...}
else if (c==d) {...}
else if (e==f) {...}

Because according to me, they both look the same and I can't find any
advantage with the "else if" statement

JollyK
 
Hi,

There's a big difference.
Let's take your 2 pieces of code and make an example of it

We say that:
int a=1, b=1, c=2, d=3, e=4, f=5;

The first code:
if (a == b) { Code here will be executed }
if (c==d) { Code here will not be executed }
if (e==f) { Code here *will* be executed }

The second code:
int a=1, b=1, c=2, d=3, e=4, f=5;
if (a == b) { Code here will be executed }
else if (c==d) { Code here will not be executed }
else if (e==f) { Code here *will not* be executed (because a==b) }

Hope this helps,

Nico Vrouwe
 
Daah, typo.
I meant: e=4, f=4; so e==f.

No flames thank you ;)

/Nico


Nico Vrouwe said:
Hi,

There's a big difference.
Let's take your 2 pieces of code and make an example of it

We say that:
int a=1, b=1, c=2, d=3, e=4, f=5;

The first code:
if (a == b) { Code here will be executed }
if (c==d) { Code here will not be executed }
if (e==f) { Code here *will* be executed }

The second code:
int a=1, b=1, c=2, d=3, e=4, f=5;
if (a == b) { Code here will be executed }
else if (c==d) { Code here will not be executed }
else if (e==f) { Code here *will not* be executed (because a==b) }

Hope this helps,

Nico Vrouwe


JollyK said:
Hello folks, So what is the difference between

Code:
if (a == b) {...}
if (c==d) {...}
if (e==f) {...}

and

Code:
if (a == b) {...}
else if (c==d) {...}
else if (e==f) {...}

Because according to me, they both look the same and I can't find any
advantage with the "else if" statement

JollyK
 
Nico said:
Daah, typo.
I meant: e=4, f=4; so e==f.

No flames thank you ;)

/Nico

Dodgy figures ;-)
Also look here: http://csharp-station.com/Tutorials/Lesson03.aspx
It really all depends on whether all three should be checked ALL the
time, or whether checking the second and third is somehow conditional
depending on the result of the first.
There is a big difference and you should really try to understand it.

S.
 
Back
Top