A generalization of <=> and swap(&x, &y)

Greg Davidson davidson at sdcsvax.UUCP
Thu Feb 14 17:48:33 AEST 1985


I hope no one is taking seriously the idea that any new operators might
be added to C at this point.  But the subject of swap operators and
swap functions reminds me of Suzuki's [1] pseudo parallel pointer rotation
functions which I borrowed for C from LISP.  Here's how they work:

Define:
	assign( &var1, val1, &var2, val2, ..., &varn, valn, NULL)
as a function which assigns each value into the address on its left.
If any of the sources are the same as any of the destinations, there
will be no order effects because the values are all being copied out
before the assignment takes place (pseudo-parallel assignment).

Then define:
	shift( &var1, ..., &varn, val, NULL )
be the same as:
	assign( &var1, var2, &var2, var3, ..., &varn, val, NULL );

And define:
	rotate( &var1, ..., &varn, NULL )
is the same as:
	shift( &var1, ..., &varn, var1, NULL );

I first wrote these as macros in LISP, but since the C Preprocessor
is too weak for such things, I coded them up as functions in C using
VARARGS, with a NULL pointer to terminate the list.  Also, in C they
only work for pointers (again because they can't be written as macros).

So why are these so useful?  Well, it turns out that lots of fancy
pointer manipulating algorithms involve shifting & rotating groups
of pointers, and if you don't have to worry about the alias & overlap
problems (which these routines free you from) its really nice.  For
example, they simplify the implementation of AVL trees.

It really is a shame that the C preprocessor is too weak to write such
things as macros, because you really don't want there to be any extra
overhead for such low level operations.

[1] Suzuki, Norihisa.  ``Analysis of Pointer `Rotation'.''  Comm. ACM
    25:5 (May 1982), 330-335.

_Greg



More information about the Comp.lang.c mailing list