开发者

Multiple IFs with the same return

I've seen some code that looks like this:

if (a) return false;
if (b) return false;
if (c) return false;
return true;

Is there any difference in performance between the above and

if (a || b || c) return false;
else return true;

In general, what would be the preferred case to handle this? Maybe without the else in my second example?

EDIT: It seems a lot of people were mislead by the fact that I return true or false and suggest returning !(a || b || c). This wasn't what I wanted to ask. I开发者_如何学Pythonmagine if instead of returning true or false I want to return "Yes" or "No", or 23423 or 3.


The only advantage to either one would be readability, it would be reasonable for an optimizing compiler to generate nearly identical code for the two cases.

If the 3 tests are short then return !(a||b||c); is perfectly reasonable

If however they are long function calls then your first example would be easier to read.


It all comes down to how the compiler compiles the code. For all practical purposes, they are identical. (As long as you make sure to use short-curcuited OR "||")


In short: there are no significant differences in the code, and you could further shorten your code by writing it as return !(a || b || c);


If your conditions are really simple, for example if (fata_is_invalid || login_failed) then you could combine them all into one line like you suggested.

Sometimes you will see conditions that are simply massive, and in that case it's preferable to split them up into smaller chunks (either through multiple if-statements or by re-formatting your code). Either way, it is just a readability thing - use whatever method you prefer (or whatever is advocated by your "style guide").

The compiler is super-sweet and will produce (almost) identical code for whatever you write in those cases.


&&, || and ? are short-circuit operators in C++, which means that the second argument is evaluated only if the first is not determining the value of the expression.

That means you could simply write, for your sample code:

return !(a || b || c);


Separate ifs and using || operator are not neccessarily identical! If any of a, b or c are user defined types and overload either || or conversion operator to any integer or pointer type then the two constructs may yield different results!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜