swap() macro

Wayne Throop throopw at dg_rtp.UUCP
Tue Jun 24 05:49:50 AEST 1986


> Schauble at MIT-MULTICS.ARPA
> Can someone construct a version that makes
>     int *a, *b;
>     swap (*a++,*b++);
> work right?

Yes.  It's rather simple actually.  Based on an idea I posted a couple
of weeks ago.  (I am assuming by "work right", you mean that it acts
like you wrote {tmp = *a; *a = *b; *b = tmp; a++; b++;} )

        #define swap(a,b) \
        {   int *pa = &(a), *pb = &(b), tmp;\
            tmp = *pa; *pa = *pb; *pb = tmp;\
        }

Naturally, this version is less efficent than the more usual swap
macros, it can't be applied to register variables, and it might cause
problems if used something like "if(foo) swap(a,b); else bar();", which
looks like it ought to work but actually willn't.  Despite these
problems, it does fit the description of what was wanted.


This leads to an interesting portability/maintainability/debugability
check that lint might be enhanced to do.  (Yes, I said the dirty word
"portability".  Root Boy can now tune out...).

Consider a function declared like so:

    /*MACROLIKE*/ int f();

If lint would generate warnings when arguments with side-effects are
passed to "f", it would then be possible to find all such places and
"fix" them so that the function f could be replaced by a macro.  For
another use, during debug f could be a function (so that it could be
"traced" in dbx, for example), and yet when it passed this lint check it
could safely be replaced by a macro in a "production" version, and have
a good chance of not breaking.

--
"... and my name is 'Sylvester', not 'George'!"
"But I can't say 'Sylvester', George."
-- 
Wayne Throop      <the-known-world>!mcnc!rti-sel!dg_rtp!throopw



More information about the Comp.lang.c mailing list