0

If A is false, then A && B is false, so there is no need to check B. So very often, the compiler writes assembly in such a way that if A && B is to be evaluated and A is evaluated as false, then B is not evaluated.

Can I assume that that all compilers which adhere to ISO standard (let's say C99 or more modern), will behave like this?

The reason I ask is that in my program, I have the statement if (i > -1 && x[i] > 3). So if i is negative but x[i] > 3 still gets evaluated, this will lead to a segmentation fault.

user56202
  • 299
  • 1
  • 9

1 Answers1

4

Yes, the ISO C standard does guarantee short-circuit evaluation for the && operator.

§6.5.13 ¶4 of the ISO C11 standard states the following:

Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39