Some functions which calculate booleans:
bool a()
{
return trueorfalse;
}
bool b()
{
//...
}
bool c()
{
//...
}
This condition
//somewhere else
if((a()&&b()&&c()) || (a()&&b()&&!c()) )
{
doSomething();
}
can also be written as
if(a()&&b())
{
doSomething();
}
Will compilers usually optimize this away?
And what about pure boolean values:
if((a&&b&&c) || (a&&b&&!c))
{
doSomething();
}
Since the functions may have side effects, the conditional cannot be "optimized" in any way, since all the functions will have to be called (conditionally) in a well-defined manner.
If you do want optimization, you can assign the result to variables first:
const bool ba = a(), bb = b(), bc = c();
if (ba && bb && bc || ba && bb && !bc) { /* ... */ } // probably optimized to "ba && bb"
It's possible that constexpr
functions introduced in C++11 will allow for optimization if they yield a constant expression, though, but I'm not sure.
You can even condense this down: In the following code, f()
has to be called twice:
if (f() && false || f() && true)
{
// ...
}
No they won't. The reason why is that the optimization would be visible to the user because it would change the observable side effects. For example In your optimized version c()
would never execute even though the user explicitly tried to do so. This can and will lead to bugs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With