cast changes meaning of auto-increment?

Mikael Pettersson mikpe at mina.liu.se
Mon Sep 12 12:31:30 AEST 1988


Consider the following piece of code:
--begin-example--
{
	int i = 27;
	register char *cp, *oldcp;

	oldcp = cp = (char *)&i;
	printf("i == %d, ", *(int *)cp++);		/* should print `27' */
	printf("and cp increased by %d\n", cp-oldcp);	/* 4 or 1 ? */
}
--end-of-example--
My question is: what should be printed by the second printf, 4 or 1?
Many PCC-based m68k compilers (including SUN's) print `4' but I know of at
least two (GCC on our SUNs and GOULD's UTX/32 compiler) that insist on
printing `1'.

Since a cast doesn't produce an lvalue, I assume the ++ should be applied
to `cp' after the int was fetched (i.e., cp should increase by 1), but the
other (buggy?) behaviour could come in handy when writing fast C
versions of the bcopy/memcpy family.


/Mike
-- 
Mikael Pettersson           ! Internet:mpe at ida.liu.se
Dept of Comp & Info Science ! UUCP:    mpe at liuida.uucp  -or-
University of Linkoping     !          {mcvax,munnari,uunet}!enea!liuida!mpe
Sweden                      ! ARPA:    mpe%ida.liu.se at uunet.uu.net



More information about the Comp.lang.c mailing list