I always dare NOT to code like this:
void func( some_struct* ptr ) {
if ( ptr != nullptr && ptr->errorno == 0 )
do something...
};
instead I always do like this:
void func( some_struct* ptr ) {
if ( ptr != nullptr )
if ( ptr->errorno == 0 )
do something...
};
because I'm afraid that the evaluation order of logical operator && is un-specified in C++ standard, even though commonly we could get right results with almost all of nowdays compilers. In a book, 2 rules let me want to get known exactly about it.
My question is : Without overloading, is the evaluation order of logical operator "&&" and "||" definite?
Sorry about my ugly English, I'm a Chinese. and I apologize if there is a duplicated topic, because I can't finger out correct key-words to search with. Thanks anyway!
Yes, it's guaranteed for built-in logical AND operator and logical OR operator by the standard.
(emphasis mine)
The && operator groups left-to-right. The operands are both contextually converted to bool. The result is
true
if both operands aretrue
andfalse
otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand isfalse
.
The || operator groups left-to-right. The operands are both contextually converted to bool. The result is
true
if either of its operands istrue
, andfalse
otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates totrue
.