What does ANSI C say about short circuit evaluation?

der Mouse mouse at thunder.mcrcim.mcgill.edu
Sat May 25 23:03:44 AEST 1991


In article <1991May22.092404.25297 at ucthpx.uct.ac.za>, gram at uctcs.uucp (Graham Wheeler) writes:

> i) Does ANSI C say that compilers can rearrange the order of
>    expression evaluation?

In general, yes.  There are a few exceptions; notably, the &&, ||, ?:,
and , operators promise some things about the order in which their
operands are evaluated (and in some cases, about whether certain
operands are evaluated at all).

> ii) Does it say that Boolean expressions must be evaluated with
>     short-circuit evaluation?

When using the short-circuit operators && and ||, yes.

> We think the answers to both of these are yes, but we aren't sure.

Mostly.  The second one is yes; the first one is a qualified yes.

> This would mean that a statement like:

>       if (ptr && ptr->next) ...

> could potentially cause a segmentation violation on a system with
> meory protection if the compiler was stupid enough to try to evaluate
> the second (more complex) subexpression first - ie, one cannot rely
> on short-circuit evaluation to prevent this from happening.

No, this is not a danger.  A compiler producing code for that example
that evaluates ptr->next when ptr == 0 (ie, when ptr is a null pointer
of its type) is simply broken.

                                        der Mouse

                        old: mcgill-vision!mouse
                        new: mouse at larry.mcrcim.mcgill.edu



More information about the Comp.lang.c mailing list