开发者

Will the 2nd conditional in an OR ever be executed if the 1st conditional passes?

开发者 https://www.devze.com 2023-03-22 23:13 出处:网络
For example: if(pos == -1 || character_ar开发者_如何学Goray[pos] == 0) { } If pos is -1, can I count on this NEVER crashing?

For example:

if(pos == -1 || character_ar开发者_如何学Goray[pos] == 0) {

}

If pos is -1, can I count on this NEVER crashing?

Same goes with AND statements in which the first conditional fails.


C supports short-circuit evaluation with the logical || and && operators, so in your case it should work as you describe, i.e. not crash.


This is language specific, but most languages will ignore the rest of the statement if the first part is true for a ||.

Similarly, most languages will ignore the rest of the statement if a part of a && is false.

If you want everything to be executed, then use the single | and & operators instead.


Yes, you can count on this. The relevant parts of the C standard are 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.

and 6.5.14:

Unlike the bitwise | 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 unequal to 0, the second operand is not evaluated.

For example, the following is idiomatic C:

if (foo && foo->bar > 10)
0

精彩评论

暂无评论...
验证码 换一张
取 消