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 to0
, 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 to0
, the second operand is not evaluated.
For example, the following is idiomatic C:
if (foo && foo->bar > 10)
精彩评论