+ 2

if/else if differences

Can someone please explain the difference between the following code for me? if (condition) { code to run } else if (condition2) { other code } else if (condition3) { more code } else{ default code } ------------- if (condition) { code to run } else { if (condition2) { other code } else { if (condition3) { more code } else { default code } } } is it purely readability that makes it different?

14th Mar 2017, 2:16 AM
Luke Armstrong
4 odpowiedzi
+ 4
Well, I believe that it would all depend on the conditions you are checking. For example (pseudo-code): if (A && B) { } elseif (A && C) { } elseif (A && D) { } In this example, there's a common condition shared between all ifstatements, which means that re-writing to the following is probably more efficient: if (A) { if (B) { } elseif (C) { } elseif (D) { } } However, if you cache the result of the Acondition. The performance gains would probably minimal. Perhaps there are even optimizations performed by the compiler, so you would have to run a performance test to make sure there's even a difference in execution time. More importantly, unless you are writing some performance-critical code, always try to write code by focusing on readability. There's almost always an efficient way of flattening conditionnal statements without hurting efficiency anyway.
14th Mar 2017, 2:48 AM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 2
Yes, there is absolutely no difference between if ( ) { } elseif ( ) { }. or. if ( ) { } else { if ( ) { } } It depends on you how you use them but most of the coders prefer the if..elseif...else 'coz the curly brackets are easy to manage and there is no chance of errors
14th Mar 2017, 2:41 AM
Prakhar Saxena
Prakhar Saxena - avatar
+ 2
python's 'elif' is way more neat, IMHO of course)
24th Apr 2017, 2:31 PM
Yury De Lorenzis-Polezhaev
Yury De Lorenzis-Polezhaev - avatar
0
Thank you both!
18th Mar 2017, 6:50 AM
Luke Armstrong