Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!cmcl2!rutgers!mtune!codas!cpsc6a!rtech!wrs!dg From: dg@wrs.UUCP (David Goodenough) Newsgroups: comp.lang.c Subject: Re: typeof isn't enough to define swap correctly Message-ID: <343@wrs.UUCP> Date: Tue, 8-Sep-87 19:53:47 EDT Article-I.D.: wrs.343 Posted: Tue Sep 8 19:53:47 1987 Date-Received: Fri, 11-Sep-87 02:00:14 EDT References: <557@rocky.STANFORD.EDU> Reply-To: dg@wrs.UUCP (David Goodenough) Organization: Wind River Systems, Emeryville, CA Lines: 45 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. Actually its almost trivial: create swap.h: #define swap(a, b) _swap_(&a, &b, sizeof(a)) static _swap_(p1, p2, count) char *p1, *p2; { char x; while (count--) { x = *p1; *p1++ = *p2; *p2++ = x; } } And you're open for business. Of course you may need to throw some other stuff in there to get lint to shut up, but the above does work. (If you want to get industrious (as I did) put _swap_() in a library - saves having a copy for each file that includes swap.h). And before anyone starts bitching about the &a and what do you do with a swap(a, 0) or swap(a, b + 5) both args should be lvalues and hence &-able -- dg@wrs.UUCP - David Goodenough +---+ | +-+-+ +-+-+ | +---+