swap() macro
Chris Torek
chris at umcp-cs.UUCP
Wed Jul 2 05:17:48 AEST 1986
In article <1836 at brl-smoke.ARPA> gwyn at brl.arpa (Doug Gwyn
(VLD/VMB) <gwyn>) writes:
>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".
How so? It seems rather simple. I have here a C program that effects
call-by-name and does indeed perform a swap:
/*
* Call by name example of swap.
*
* Call by name is done by passing `thunks', where a `thunk' is a
* function that returns the address of an argument. In this case
* calling the function provided via `f1' returns the address of
* the first argument; indirecting through this address produces
* the argument itself, as an lvalue (i.e., `named'). Similarly,
* indirection through f2's return value names the second argument.
*/
swap(f1, f2)
int *(*f1)(), *(*f2)();
/* `pointer to function returning pointer to int' */
{
int t;
t = *(*f1)();
*(*f1)() = *(*f2)();
*(*f2)() = t;
}
/*
* Here are the variables we will address for swap().
*/
int a, b;
/*
* Here are the two `thunk' functions.
*/
int *
addr_a()
{
return (&a);
}
int *
addr_b()
{
return (&b);
}
/*
* Finally, demonstrate that swap() does indeed work:
*/
/*ARGSUSED*/
main(argc, argv)
int argc;
char **argv;
{
a = 3;
b = 7;
swap(addr_a, addr_b);
printf("should be 7, 3: a = %d, b = %d\n", a, b);
exit(0);
}
/*
* Incidentally, `swap' can be passed a thunk that names an expression;
* here is what a call-by-name compiler might generate for `a+b':
*
* int *
* addr_aplusb()
* {
* int t = a + b;
*
* return (&t);
* }
*/
--
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