简体   繁体   中英

If-Statement in C++ with empty body: is condition guaranteed to be evaluated?

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.)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM