This question pertains to pretty much all C-like "curly bracket" programming languages.
I'm talking about using the following:
if(condition)
meh();
else if(condition1)
bleh();
else if(condition2)
moo();
else
foo();
Are there any caveats to be aware of when using this idiom in code? I'm looking for things like performance penalties, compiler limits, etc. What would a typical compiler do with something like this?
I ask because even though it looks nice and flat to the human eye, it would actually be strictly parsed as equivalent to the following, with the braces added:
if(condition)
{
meh();
}
else
{
if(condition1)
{
bleh();
}
else
{
//...
}
}
i.e. the else if
is not really a delimiter; instead each if
would be nested inside the preceding else
. It would be like parsing x+y+z+... as x+(y+(z+...)).
Do compilers actually treat it this way, or would they treat else if
as a special case? If the former, what caveats would I have to be aware of?
(This is my first question on StackOverflow.)
Use the variant with
else-if
wherever possible. This construct does not have disadvantages.It is true that it is not possible to guarantee anything about the compiler optimization. At the same time experience and reasonable thinking both tell that constructs of this complexity is not a problem for modern-days compilers.