swap(x,y)

Maarten Litmaath maart at cs.vu.nl
Wed Aug 23 02:02:58 AEST 1989


tromp at piring.cwi.nl (John Tromp) writes:
\...
\x^=y^=x^=y;

Evaluation order undefined.  Although it works on most compilers (notable
exception: Amsterdam Compiler Kit acc), the compiler is free to rearrange
the expression as follows:

	tmp = x;
	x ^= y;
	y ^= x;
	x = tmp ^ y;

ACK lint(1) will catch this one.  NONE of the other lint(1)s I've tried did
(BSD, SunOS, SysV).
I discovered this lint bug when trying to compile the following program with
acc (my 1988 Obfuscated C Code Contest winning entry):

main(argc, argv)
int	argc;
char	**argv;
{
	while (*argv != argv[1] && (*argv = argv[1]) && (argc = 0) || (*++argv
		&& (**argv && ((++argc)[*argv] && (**argv <= argc[*argv] ||
		(**argv += argc[*argv] -= **argv = argc[*argv] - **argv)) &&
		--argv || putchar(**argv) && ++*argv--) || putchar(10))))
		;
}

Line 7 should be changed to:

	(**argv ^= argc[*argv] ^= **argv) && (argc[*argv] ^= **argv)) &&

BTW, there's another non-portability:

	putchar(10)

which assumes ASCII.
-- 
"rot H - dD/dt = J, div D = rho, div B = 0, |Maarten Litmaath @ VU Amsterdam:
  rot E + dB/dt = 0" and there was light.   |maart at cs.vu.nl, mcvax!botter!maart



More information about the Comp.lang.c mailing list