Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!mit-eddie!uw-beaver!uw-june!uw-entropy!dataio!bright From: bright@dataio.Data-IO.COM (Walter Bright) Newsgroups: comp.lang.c Subject: Re: typeof isn't enough to define swap correctly Message-ID: <1365@dataio.Data-IO.COM> Date: Fri, 11-Sep-87 14:23:54 EDT Article-I.D.: dataio.1365 Posted: Fri Sep 11 14:23:54 1987 Date-Received: Sat, 12-Sep-87 18:52:20 EDT References: <557@rocky.STANFORD.EDU> <1880@sol.ARPA> <109@umigw.MIAMI.EDU> <2019@sfsup.UUCP> <2105@sol.ARPA> Reply-To: bright@dataio.UUCP (Walter Bright) Organization: Data I/O Corporation; Redmond, WA Lines: 34 In article <2105@sol.ARPA> crowl@cs.rochester.edu (Lawrence Crowl) writes: #/* the mechanism to construct new identifiers */ ##define concat(n,m) n/**/m # ##define swap(a,b) { \ #/* construct new type with new name */ #typedef struct { char c[ sizeof(a) ] ; } concat(swap_T,__LINE__) ; \ #/* pointers to sources allow evaluating arguments only once */ \ #concat(swap_T,__LINE__) *concat(swap_P,__LINE__) = &(a) ; \ #concat(swap_T,__LINE__) *concat(swap_Q,__LINE__) = &(b) ; \ #/* do actual swap */ #concat(swap_T,__LINE__) concat(swap_R,__LINE__) = *concat(swap_P,__LINE__) ; \ #*concat(swap_P,__LINE__) = *concat(swap_Q,__LINE__) ; \ #*concat(swap_Q,__LINE__) = concat(swap_R,__LINE__) ; \ #} #Have I forgotten anything? I know that #define swap(a,b) { typeof(a) _tmp; _tmp = a; a = b; b = _tmp; } is not completely generic. But it is at least readable, simple, compiles efficiently, and works for variables, register variables, structs and unions. As far as swap(a++,b++) goes, who cares? Good coding style should preclude that occurrence. If you have a name collision with _tmp, your program is probably a candidate for the Obfuscated C Contest anyway. Arrays are a special beast anyway. Very little else works with arrays. I'd rather have swap work with register variables than with arrays. To summarize, I would prefer a simple macro with obvious limitations to a complex macro with very obscure limitations. A completely foolproof swap() would have to be implemented within the compiler anyway.