Extending the question What happens if the first part of an if-structure is false?
for C programming
if((NULL!=b)&&(query(&b)))
In the above code will the part "query(&b)" is executed if b=Null? And is the behavior consistent across compilers?
Extending the question What happens if the first part of an if-structure is false?
for C programming
if((NULL!=b)&&(query(&b)))
In the above code will the part "query(&b)" is executed if b=Null? And is the behavior consistent across compilers?
No, logical operators in C will short-circuit.
If you attempt to evaluate a && b
when a
is false, b
is not evaluated.
But keep in mind that you're not checking b
with that original statement, rather you're checking a
. Also note that it's safe to take the address of a variable that's NULL, you just can't dereference it.
I suspect what you should be writing is:
if ((b != NULL) && (query (*b)) ...
To add to the correct answers already posted this is what the C99 standard says (section 6.5.13 Logical AND operator, paragraph 4):
Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares equal to 0, the second operand is not evaluated.
In the above code will the part "query(&b)" is executed if b=Null?
Simple answer NO. It will not be executed. &&
is short circuited. So if you try to do so, this will break the short circuit evaluation, and is therefore not reccomended.
Check FAQ3.6
It is not specific to the if
statement, but rather to boolean expressions in general.
In a && b
, b
is not evaluated if a
is false.
Similarly in c || d
, d
is not evaluated if c
is true.
This is known as short-circuit evaluation and is part of the definition of the language, so will be consistent across compliant compilers.