If-Statement in C ++ with an empty body: is a condition guaranteed for evaluation?

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

if( doSomething() ) {} 

Does the "C ++ Standard" guarantee that a function is called? (This return value does not affect the execution path, so the compiler can follow the ideas of label evaluation and optimize it.)

+8
c ++
source share
1 answer

The short circuit operator is not involved, so the function will be guaranteed to be called if it cannot be optimized without eliminating side effects. Citation of the C ++ 11 standard:

[...] corresponds to the implementation required to emulate (only) the observed behavior of an abstract machine, as explained below. 5

5 This provision is sometimes called the “as-if” rule [...], the actual implementation should not evaluate part of the expression if it can infer that its value is not used and that there are no side effects affecting the observed behavior of the program.

So, something like

 int doSomething() { return 1; } 

can be optimized but

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

is not allowed.

Also, since C ++ 11, you can write more complex functions and still evaluate them at compile time using constexpr .

+8
source share

All Articles