Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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

like image 908
philipp Avatar asked Oct 22 '15 09:10

philipp


People also ask

What happens if there is no condition in if statement?

C - General Programming - Return value of a if statement without any condition. To test a condition in a if statement without any condition, the result has to be other than 0 to test a true condition. Result: $ True - Value was -1.

Can we use if without condition?

If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed. On the other hand if you need a code to execute “A” when true and “B” when false, then you can use the if / else statement.

How does if statement work in C?

C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

What is simple if statement in C?

if statement in C/C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.


1 Answers

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.

like image 141
cadaniluk Avatar answered Oct 13 '22 19:10

cadaniluk