Search code examples
cif-statement

In C whether the second part of if structure is executed if first logical part failed? Is the behavior compiler depended?


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?


Solution

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