8

Given this statement (which, as a sidenote, is not my preferred coding style)

if( doSomething() ) {}

Does 'the C++ Standard' guarantee that the function is called? (It's return value has no effect on the execution path, so the compiler may follow the ideas of shortcut evaluation and optimize it away.)

philipp
  • 1,745
  • 1
  • 14
  • 25
  • 2
    Yes, the standard guarantees it and an optimizer isn't allowed to change the semantic effect. –  Oct 22 '15 at 09:14
  • You can just write `(void) doSomething();` if you want to explicitly discard the return value. – Useless Oct 22 '15 at 09:19

1 Answers1

8

There's no short-circuit operator involved, so the function is guaranteed to be called if it can't be optimized away without removing side-effects. Quoting the C++11 standard:

[...] conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.5

5 This provision is sometimes called the “as-if” rule [...] an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced.

So, something like

int doSomething() { return 1; }

might be optimized away, but

int doSomething() { std::cout << "d\n"; return 1; }

isn't allowed to.

Additionally, since C++11, you can write more sophisticated functions and still make them evaluated at compile time by using constexpr.

Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67