Brain Teaser

Tim McDaniel mcdaniel at amara.uucp
Wed Mar 28 11:01:11 AEST 1990


oesterle at wpi.wpi.edu (Shawn H. Oesterle) asks how to swap two pointers
without using a third pointer.

Swap-macros-that-use-no-intermediate-variables appear in comp.lang.c
every so often.  They usually use exclusive-OR, and hence only work
for integral types.  Oesterle's Variant,
           x += y; y = x - y; x -= y;
can fail if an intermediate expression overflows.

You can't do portably swap arbitrary legal pointer values without
using an intermediate variable.  In short, "no".

(I've never had a problem scrounging data space for an intermediate
value, and I *never* want to burn the extra CPU time or risk overflow.
If this discussion is fresh and interesting to you, I'm glad, and you
have a perfect right to discuss it in comp.lang.c all you want.  But
I'm sorry to tell you I'm an old sourpuss, and I'm afraid that this
subject is going into my KILL file immediately.)

--
Tim McDaniel
Applied Dynamics International, Ann Arbor, MI
Internet: mcdaniel%amara.uucp at mailgw.cc.umich.edu
UUCP: {uunet,sharkey}!amara!mcdaniel



More information about the Comp.lang.c mailing list