Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!caip!topaz!harvard!seismo!umcp-cs!chris From: chris@umcp-cs.UUCP (Chris Torek) Newsgroups: net.lang.c Subject: Re: swap() macro Message-ID: <2225@umcp-cs.UUCP> Date: Tue, 1-Jul-86 15:17:48 EDT Article-I.D.: umcp-cs.2225 Posted: Tue Jul 1 15:17:48 1986 Date-Received: Wed, 2-Jul-86 06:33:22 EDT References: <1201@brl-smoke.ARPA> <193@stracs.cs.strath.ac.uk> <733@ho95e.UUCP> <1836@brl-smoke.ARPA> Reply-To: chris@maryland.UUCP (Chris Torek) Organization: University of Maryland, Dept. of Computer Sci. Lines: 84 In article <1836@brl-smoke.ARPA> gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) 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@umcp-cs ARPA: chris@mimsy.umd.edu