+ 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?
4 Respostas
+ 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.
+ 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
+ 2
python's 'elif' is way more neat, IMHO of course)
0
Thank you both!