top | item 34846235

(no title)

zooweemama | 3 years ago

Pretty sure that the compiler optimizes this and there is no performance loss.

discuss

order

meindnoch|3 years ago

You're wrong.

  if (cheapCheck() && expensiveCheck()) { ... }
is not equivalent to

  bool cheap = cheapCheck();
  bool expensive = expensiveCheck();
  if (cheap && expensive) { ... }
unless we're in a lazy pure functional language.

IshKebab|3 years ago

That depends. In some cases the compiler will be able to determine that `expensiveCheck()` has no side effects and make them equivalent. But you can't really rely on it.

And in any case the author misidentified the problem and solution. The problem is that C++ coerces bool to int. I'm 99% sure there's a warning for that that you can turn into an error.

grok22|3 years ago

In theory, if this is the case (or the case in other comments about null pointer use and such), you would/could write it as:

   bool cheap = cheapCheck();
   bool expensive = cheap && expensiveCheck();
   if (expensive) { ... }

lazypenguin|3 years ago

Can you prove this?