The difference between else if and else {if}

Viewed 71

Code A:

if () 
...
else {
   if (cond == 1) 
       /* do something */ 
}

Code B:

if ()
...
else if (cond == 1) 
   /* do something */

If there exists differences between code A and Code B?

2 Answers

There only is a potential difference, which becomes visible with slightly extended example code
(please excuse the intentionally misleading indentation, it is exactly the problem you need to keep in mind in this kind of situation):

if () 
...
else {
   if (cond == 1) 
       do_something();     /* executed on !1st and 2nd condition */
       do_somthing_else(); /* executed on !1st but unaffecated by 2nd condition */
}
if ()
...
else if (cond == 1) 
    do_something();       /* executed on !1st and 2nd condition */
    do_something_else();  /* ALWAYS executed */

There is none. There is even no difference to this code:

if ()
...
else if (cond == 1) 
...
else if (cond == 2) 
...
else if (cond == 3) 

You usually see else { if() } in this kind of code:

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

Related