swap() macro

Chris Torek chris at umcp-cs.UUCP
Wed Jul 2 14:51:40 AEST 1986


In article <1836 at brl-smoke.ARPA> gwyn at brl.arpa (Doug Gwyn (VLD/VMB)
<gwyn>) wrote:
>>It may be amusing and/or instructive to contemplate the fact that
>>there is no way to write a function that exchanges the contents of
>>two variables in a language where parameters are passed "by name".

In article <2225 at umcp-cs.UUCP> I replied:
>I have here a C program that effects call-by-name and does
>indeed perform a swap:

What I failed to consider, of course, is the classic problem with
call by name: arrays.  Watch what happens when I `swap' `i' and
`a[i]', using an expanded form of the swap function (this is
necessary to avoid compiler dependencies in this particular case).

Ah well, at least I caught my error myself. . . .

swap(f1, f2)
	int *(*f1)(), *(*f2)();
{
	int t1, t2;

	t1 = *(*f1)();
	t2 = *(*f2)();
	*(*f1)() = t2;
	*(*f2)() = t1;
}

int	a[10], i;

int *
addr_asubi()
{

	return (&a[i]);
}

int *
addr_i()
{

	return (&i);
}

/*ARGSUSED*/
main(argc, argv)
	int argc;
	char **argv;
{

	a[3] = 6;
	a[6] = 1;
	i = 3;
	swap(addr_i, addr_asubi);

	/*
	 * Want i to become 6 and a[3] to become 3, with a[6] left
	 * undisturbed.  That is not what happens.  Figure out what
	 * it will in fact do, before you run it.
	 */
	printf("`should' be 6, 3, 1: i = %d, a[3], a[6] = %d\n",
		i, a[3], a[6]);
	exit(0);
}
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 1516)
UUCP:	seismo!umcp-cs!chris
CSNet:	chris at umcp-cs		ARPA:	chris at mimsy.umd.edu



More information about the Comp.lang.c mailing list