c++ standard question (solved)

Started by
2 comments, last by Oxyd 15 years, 8 months ago
Hello, as in the subject - let's say I have the following expression (simplified - false may be some kind of logical check, foo is a function / method name): if ( false && foo() ) { ... } Now I know about operations precedence and that this is an example of bad practice (side effects in 'if') etc.. The question is if C++ standard in 100% guarantees that funtion foo() won't be invoked? Or maybe it is a compiler dependant behaviour? In other words: if some compiler processes both 'false' and 'foo()' statements than does it mean that it is not C++ standard compliant? Thank you, BR, [Edited by - mzworowski on July 29, 2008 8:54:28 PM]
Advertisement
correct, foo() should never get processed. Otherwise things like this would crash:

void something( SomeClass *poop ){    if ( poop && poop->IsDead() )    {        return;    }}


What compiler are you using. If you say Microsoft Visual Studio 6.0 you should have upgraded ~3 years ago when the 2005 express edition was made free [smile]

-me
I'm using some decent gcc on Linux / Solaris, target PowerPC. But the question is not related to any specific compiler. I was just curious what ISO / ANSI specification says about this.
I understand that there is an explicit statement in specification that in case of '&&' operator - when left operand logical result is 'false' than the right side expression shall / must not be processed. Correct?

Thanks for help,
BR
Yes, the two built-in operators && and || have short-circuit semantics as per the ISO/IEC 14882:2003 standard. There is also a sequence point between the two operands.

Quote:5.14.1 of the Standard
The && operator groups left-to-right. The operands are both implicitly converted to type bool (clause 4). The result is true if both operands are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.
Quote:5.15.1 of the Standard
The || operator groups left-to-right. The operands are both implicitly converted to bool (clause 4). It returns true if either of its operands is true, and false otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.

Note, however, that the above does not hold for overloaded operators && and ||. If you overload && or || and the expression resolves to calling this operator, rules for calling regular function apply here -- so no sequence point between operands and no short-circuit evaluation for overloaded operators, only built-in operators short-circuit.

This topic is closed to new replies.

Advertisement