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; if ( 0!=ptr && ptr->some_flag ) { }
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
source share