Multiple IFs with the same return

I saw code that looks like this:

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

Is there a performance difference between above and

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

In general, what would be preferable for this? Maybe without the rest in my second example?

EDITOR: It seems that many people have been misled by the fact that I am returning truth or falsehood and offering to return! (a || b || c). This was not what I wanted to ask. Imagine that instead of returning true or false, I want to return β€œYes” or β€œNo”, or 23423 or 3.

+6
source share
5 answers

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

+4
source

The only advantage of one of them is readability, it would be reasonable for the optimizing compiler to generate almost identical code for two cases.

If 3 tests are short, then return !(a||b||c); quite reasonable

If, however, these are long function calls, your first example will be easier to read.

+5
source

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


If your conditions are really simple, for example if (fata_is_invalid || login_failed) , you can combine them all in one line, as you expected.

Sometimes you will see conditions that are simply massive, and in this case it is preferable to divide them into smaller pieces (either with the help of several if-statements or by reformatting your code). In any case, it's just readability - use whatever method you prefer (or whatever is protected by your "style guide").

The compiler is super-sweet and will generate (almost) identical code for everything you write in these cases.

+1
source

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

This means that you can simply write code for your sample:

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

Separate ifs and using || The operator is not necessarily identical! If any of a, b or c is a user-defined type and overloads either || or a conversion operator to any integer or pointer type, the two constructs can give different results!

0
source

Source: https://habr.com/ru/post/891528/


All Articles