Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can/do compilers simplify logical expressions involving functions?

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();
}
like image 866
TravisG Avatar asked Jan 19 '23 20:01

TravisG


2 Answers

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)
{
  // ...
}
like image 76
Kerrek SB Avatar answered Jan 30 '23 12:01

Kerrek SB


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.

like image 22
JaredPar Avatar answered Jan 30 '23 14:01

JaredPar