0

Possible Duplicate:
Is short-circuiting boolean operators mandated in C/C++? And evaluation order?

Consider this code:

char* str=NULL;
if(str!=NULL && str[0]=='h')
    printf("ok");

The first condition verified is that str is not NULL.I have tried to compile and run this code, and I don't get segmentation fault.
This means that the code breaks at the next instruction out the if, because is not needed to further verify that str[0] is equal to 'h', because it's an and.
But the question is: is this guaranteed to work with all compilers? Can't happen that the compiler generates assembly code that for some reason, first verifies that str is equal to 'h' (causing segmentation fault), and then checks that str is not NULL?

Community
  • 1
  • 1
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
  • If the compiler calls itself a Standard C compiler, it must do as you say. If it doesn't, then the compiler is buggy. – pmg May 01 '12 at 15:40

2 Answers2

3

Yes, this is guaranteed. It is called short-circuit evaluation.

From the C99 standard (section 6.5.13):

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.

A similar rule applies to ||; if the first operand is true, then the second is not evaluated.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
0

Yes. That is how it is supposed to work.

unexpectedvalue
  • 6,079
  • 3
  • 38
  • 62