user818794
user818794

Reputation: 73

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. Imagine if instead of returning true or false I want to return "Yes" or "No", or 23423 or 3.

Upvotes: 6

Views: 457

Answers (5)

Tomek
Tomek

Reputation: 4659

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!

Upvotes: 0

RAY
RAY

Reputation: 7090

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 "||")

Upvotes: 4

Marius Bancila
Marius Bancila

Reputation: 16318

&&, || 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);

Upvotes: 0

evgeny
evgeny

Reputation: 2584

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.

Upvotes: 1

tobyodavies
tobyodavies

Reputation: 28089

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.

Upvotes: 5

Related Questions