Beautiful side-effects! (q = q++)
Timothy J. Rolfe
rolfe at dsuvax.uucp
Thu Jun 27 01:47:34 AEST 1991
Beautify, beautiful side effect!!
As it stands, "q = q++;" SHOULD leave q unchanged: evaluating the
right hand side we get a value (q BEFORE the increment). That is
the value that is supposed to go to the left hand side. The question
is WHEN the post-increment is done.
On a MicroVAX-II under Ultrix we get it BOTH ways, depending on whether
we use the cc, gcc, or vcc compiler --- plain cc, GNU's cc, and VAX
native C.
We can even go better:
main()
{
int q=5, inc=10;
void kludge();
kludge (q, inc);
}
void kludge(q, inc)
int q, inc;
{
q = q++ + inc;
printf ("%d\n", q);
}
The extra level is to get around the #@$%#@ vcc compiler's optimizing
q = q++ + inc; into a simple q = 15; (since it knows the values!).
cc- and gcc-compiled versions generate an answer of 16; vcc-compiled
version generates an answer of 15.
gcc-generated machine code for kludge:
.globl _kludge
_kludge:
.word 0x0
addl2 8(ap),4(ap) ; <== calculated straight into q
incl 4(ap) ; <== then do the post-increment
pushl 4(ap) ; Assorted stuff for printf
pushab LC0
calls $2,_printf
ret
vcc-generated machine code for kludge:
kludge:
.entry kludge,^m<>
movl 4(ap),r2 ; <== get the q value
incl 4(ap) ; <== then do the post-increment
addl3 8(ap),r2,4(ap) ; <== finally calculated into q
pushl 4(ap) ; Assorted stuff for printf
pushal $CHAR_STRING_CONSTANTS
calls #2,printf
ret
--- Tim Rolfe
<a.k.a. ROLFE at SDNET.BITNET>
More information about the Comp.lang.c
mailing list