Sequence points and order of evaluation

Henry Spencer henry at utzoo.uucp
Sun Aug 7 11:19:20 AEST 1988


In article <16490004 at hpcllca.HP.COM> walter at hpcllca.HP.COM (Walter Murray) writes:
>int f(i) {printf ("%d",i); return i;}
>main ()
>{
>   (f(1)+f(2)) + (f(3)+f(4));
>   printf ("\n");
>}
>
>1.  Is this a strictly conforming program?

No, since its output depends on unspecified behavior (order of evaluation).

>2.  Is a conforming implementation required to produce a diagnostic
>    for this program?  ...

No.  The (draft) standard imposes no requirements on how this sort of
situation is dealt with.

>3.  Is a conforming implementation even required to accept
>    this program? ...

I think not, although in practice I'd be surprised to find one that didn't.

>4.  At execution, may a conforming implementation produce the
>    output "1324" for this program? ...

Yes.  The order of evaluation is "unspecified", meaning that the standard
imposes no constraints on it.

>   int temp, result;
>   result = (temp=1, temp) + (temp=2, temp);
>   printf ("result = %d\n", result);
>5.  Is this a strictly conforming program?

I believe the answer is no.  I find no prohibition on interleaving of the
evaluation of the operands of +, and in fact the second paragraph of the
introduction to 3.3 can be read as making the behavior of this program
undefined.  (Reference is to Jan draft, since I still haven't seen the May
draft.)  So this program depends on behavior that is at least unspecified
and possibly undefined, hence is not strictly conforming.

>6.  What output will this program produce on a conforming
>    implementation?

If the behavior is not undefined, then I would say the number output should
be 2, 3, or 4, the choice being the implementation's.  If it is undefined,
then it could be 987654321, or "programmer error - core dumped into source
file".

> (I've tried it on six compilers from
>    three vendors, and they all produce output which seems
>    wrong to me.)

Do not assume that existing compilers get details like this right.  Many,
many existing compilers take shortcuts in obscure corners of the language.
-- 
MSDOS is not dead, it just     |     Henry Spencer at U of Toronto Zoology
smells that way.               | uunet!attcan!utzoo!henry henry at zoo.toronto.edu



More information about the Comp.std.c mailing list