C problem, order of evaluation

Checkpoint Technologies ckp at grebyn.com
Tue Apr 10 05:07:13 AEST 1990


In article <1990Apr8.185047.7385 at diku.dk> null at diku.dk (Niels Ull Jacobsen) writes:
>I need to make an expression of the type:
>
>"( stack[++sp]= exp , stack[sp -= N])", where exp contains N "stack[++sp]"'s.
>
>The expression is supposed to have the value of the right side of the
>assignment, and to push this on the stack as well. The expression is to be a
>part of a function argument, and can therefore not contain any local block
>declarations.

As long as that comma is really the comma *operator* and not the
function argument separator, then the order of evaluation of your
subexpressions *is* guaranteed.  The left expression is evaluated first,
the comma declares a sequence point (which means that all side effects
are completed), and then the right hand side is evaluated, which becomes
the result of the whole expression.  The order is defined in both K&R C
and ANSI C.

Now, if your comma really is a function argument separator, then the
order of evaluation is not guaranteed, and your concerns are justified.
If your two subexpressions are supplying two parameters to a single
function call then you're screwed.  There's no way to make them evaluate
left-to-right in all cases, and in fact it's common to evaluate function
arguments right-to-left, because on many machines that's the order in
which they are pushed onto the stack as they become function arguments.

This seems to be a commonly misunderstood thing.  There are a few
operators whose order of evaluation *is* guaranteed, and the comma
operator is one of them.  Others are && and ||, these are always
performed left to right with a sequence point in between. There may be
others I don't remember right now. Oh, yes, the "conditional" operator ?
: is guaranteed left to right (sort of); the condition expression is
evaluated first, then a sequence point is declared, then one
of the subexpressions is evaluated but not the other.



More information about the Comp.lang.c mailing list