Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!rutgers!rochester!crowl From: crowl@cs.rochester.edu (Lawrence Crowl) Newsgroups: comp.lang.c Subject: Re: typeof isn't enough to define swap correctly Message-ID: <1880@sol.ARPA> Date: Fri, 4-Sep-87 17:52:50 EDT Article-I.D.: sol.1880 Posted: Fri Sep 4 17:52:50 1987 Date-Received: Sat, 5-Sep-87 19:57:20 EDT References: <557@rocky.STANFORD.EDU> Reply-To: crowl@cs.rochester.edu (Lawrence Crowl) Organization: U of Rochester, CS Dept, Rochester, NY Lines: 38 In article <557@rocky.STANFORD.EDU> andy@rocky.UUCP (Andy Freeman) writes: ]In article <1354@dataio.Data-IO.COM>, bright@dataio.Data-IO.COM (Walter Bright) writes: ]> ... One thing I want, which the committee always seems to poo-poo, is a ]> typeof. Having a typeof would make creation of 'generic' routines possible: ] ]> #define swap(a,b) { typeof(a) tmp; tmp = a; a = b; b = tmp; } ] ]Even given typeof, this definition of swap is buggy. (It has at least ]two bugs.) I've never figured out how to define a C swap macro that ]works - I'm willing to believe it is impossible. ] ]Anyone have a use for typeof that isn't doesn't have the major bug that ]the swap macro defined above has? The following swap macro is correct. It relies on the pointer features of C to evaluate its arguments exactly once. #define swap(a,b) { \ typeof(a) t,*p1,*p2; /* temporary and pointers to sources */ \ p1 = &(a); p2 = &(b); /* evaluate arguments exactly once */ \ t = *p1; *p1 = *p2; *p2 = t; /* do actual swap */ \ } The following example works. (Well, I substituted typeof(a) with int.) int a[] = { 0, 1, 2, 3 } ; int b[] = { 0, 1, 2, 3 } ; int i = 0 ; int j = 1 ; swap(a[i++],b[j++]); a == { 1, 1, 2, 3 }; b == { 0, 0, 2, 3 }; i == 1; j == 2; One problem still remains. What if typeof(a) != typeof(b)? -- Lawrence Crowl 716-275-9499 University of Rochester crowl@cs.rochester.arpa Computer Science Department ...!{allegra,decvax,seismo}!rochester!crowl Rochester, New York, 14627