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.)
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With