Safety Considerations for Short Circuit Assessment

Possible duplicate:
Are short-circuiting boolean operators provided for in C / C ++? And the evaluation procedure?

AFAIK Evaluation of short circuits means that a logical expression is evaluated only to the extent that we can guarantee its result.

This is a common idiom in perl, where we can write things like: (is_ok () returns a non-zero value in "OK")

is_ok() || die "It not OK!!\n"; 

instead

 if ( ! is_ok() ) { die "It not OK!!\n"; } 

This only works because the evaluation order is always from left to right and ensures that the rightmost statement is only executed if the first statement, if not false.

In C, I can do something similar:

 struct foo { int some_flag; } *ptr = 0; /* do some work that may change value of ptr */ if ( 0!=ptr && ptr->some_flag ) { /* do something */ } 

Can this type of idiom be used?

Or is it likely that the compiler can generate code that evaluates ptr->some_flag before making sure ptr is not a null pointer? (I assume that if it is not equal to zero, it indicates a certain area of ​​memory).

This syntax is convenient to use because it preserves text input without loss of readability (in my opinion, anyway). However, I am not sure that it is absolutely safe, so I would like to know more about it.

Note: if the compiler affects this, I use gcc 4.x

+4
source share
4 answers

The evaluation procedure for short-circuit operators ( || and && ) is guaranteed by the standard from left to right (otherwise they would lose some of their usefulness).

Β§6.5.13 ΒΆ4

Unlike the bitwise binary operator & the && operator guarantees an evaluation from left to right; after evaluating the first operand, there is a point in the sequence. If the first operand is compared to 0 , the second operand is not evaluated.

Β§6.5.14 ΒΆ4

Unlike the bitwise operator | operator || guarantees an assessment from left to right; There is a sequence point after evaluating the first operand. If the first operand is not equal to 0, the second operand is not evaluated.

+7
source

Or is it likely that the compiler can generate code that evaluates ptr-> some_flag before making sure that ptr is not a null pointer?

No, zero probability. It is guaranteed by the standard that ptr->some_flag will not be evaluated if the first operand is false.

6.5.13-4

Unlike bitwise binary code and operator, operator guarantees && rating from left to right; after the point the score of the first operand. If the first operand is compared to 0, the second operand is not evaluated .

+4
source
 /* do some work that may change value of ptr */ if ( 0!=ptr && ptr->some_flag ) { /* do something */ } 

Can this type of idiom be used?

Yes.

+2
source

The above example is safe, but anyone who supports such code may not understand that there is a dependency on the evaluation order and is causing an interesting error.

+1
source

All Articles