Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

c - The difference between else if and else {if}

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...