1

Let's take this C-code example:

int ID = 0;
if(  (Check(&ID) == ERROR) 
   ||(ID == -1)
){
   return ERROR;
}

Do you have any guarantee that (Check(&ID) == ERROR) is checked before (ID == -1) ?

(ID = -1 would be an error-state, set by the function Check)

user1511417
  • 1,880
  • 3
  • 20
  • 41

2 Answers2

2

Yes you do. For an expression of the form x || y, y is only evaluated if x evaluates to 0.

This is called short-circutting, and also applies to &&.

Your parentheses are also superfluous: the same applies to the equivalent (and, in my opinion, clearer)

if (Check(&ID) == ERROR || ID == -1)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Yes, because there is a sequence point between evaluation of first and second operand of || operator.

N1570 5.1.2.3 Program execution, paragraph 3 says:

The presence of a sequence point between the evaluation of expressions A and B implies that every value computation and side effect associated with A is sequenced before every value computation and side effect associated with B.

N1570 6.5.14 Logical OR operator, paragraph 4 says:

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

MikeCAT
  • 73,922
  • 11
  • 45
  • 70