'Is the "shortcut" for evaluating "A && B" part of one of the ISO standards? [duplicate]

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.

c


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andreas Wenzel