Search code examples
c++short-circuiting

Turn off || operator optimization


Is there any option in VS C++ 2017 so that when it builds the following program both f() and g() are called?

#include <iostream>
using namespace std;
bool f()
{
    cout << "f" "\n";
    return true;
}
bool g()
{
    cout << "g" "\n";
    return false;
}
int main()
{

    if (f() || g())
        cout << "hello";
    cin.ignore(1);
}

Solution

  • No there is not, this behavior (short-circuiting) is fundamentally part of logical operators.

    What you can do instead is use the bitwise or operator |. But make sure to add a comment stating that this is not a mistake but on purpose!

    In any case, if your function calls are not as simple as f() you should consider instead introducing a separate variable (or variables) to make it more obvious what your code is doing (calling two functions unconditionally, then using both their return values).