Execution order for if with multiple conventions

In an if statement with several conditional expressions, is the second condition fulfilled if the result of the first is clear?

Example:

if(i>0 && array[i]==0){ } 

If I change the conditional expressions, segfault may occur for negative values ​​of i, but segfault does not occur. Can I be sure that this always works or that I need to use nested if statements?

+41
c
Mar 16 '10 at 16:19
source share
3 answers

This type of rating is called short-circuiting . When the result is 100% understandable, it will not continue to evaluate.

This is actually a common programming method. For example, in C ++ you often see something like:

 if (pX!=null && pX->predicate()) { bla bla bla } 

If you change the order of the conditions, you can call the method with a null pointer and fail. A similar example in C would use a structure field if you have a pointer to that structure.

You can do something like this with or:

 if(px==null || pX->isEmpty()} { bla bla bla } 

This is also one of the reasons why it is generally recommended to avoid side effects in the if condition.

For example, suppose you have:

 if(x==4 && (++y>7) && z==9) 

If x is 4 , then y will increase regardless of the value of z or y , but if x not 4 , it will not increase at all.

+61
Mar 16 '10 at 16:20
source share
β€” -

Operators && and || ensure that the left expression is fully evaluated (and all side effects) before the right side is evaluated. In other words, operators enter a point in the sequence.

Also, if the value of an expression can be determined from lhs, rhs is not evaluated. In other words, if you have an expression of type x && y , and x evaluates to 0 (false), then the value of the expression is false regardless of y, so y is not evaluated.

This means that expressions like x++ && x++ clearly defined, since && introduces a point in the sequence.

+26
Mar 16 '10 at 16:57
source share

From project 3485 (n3485.pdf) It clearly states that

5.14 The logical operator AND [expr.log.and]

 logical-and-expression: inclusive-or-expression logical-and-expression && inclusive-or-expression 
  • && operator groups from left to right . operands are converted to context in bool (section 4). the result is true if both operands are true and false otherwise. Unlike &, && guarantees an evaluation from left to right : the second operand is not if the first operand is false.
  • The result is a bool. If the second expression is calculated, all values ​​and sides are calculated, the effect associated with the first expression is sequenced before each value calculation, and the side effect associated with the second expression is calculated.
+10
Jan 22 '14 at 12:23
source share



All Articles