prev up next   top/contents search

comp.lang.c FAQ list · Question 10.3

Q: How can I write a generic macro to swap two values?


A: There is no good answer to this question. If the values are integers, a well-known trick using exclusive-OR could perhaps be used, but it will not work for floating-point values or pointers, or if the two values are the same variable. (See questions 3.3b and 20.15c.) If the macro is intended to be used on values of arbitrary type (the usual goal), any solution involving a temporary variable is problematical, because:

The best all-around solution is probably to forget about using a macro, unless you're willing to pass in the type as a third argument. (Also, if you're trying to swap entire structures or arrays, you probably want to exchange pointers instead.) If you're worried about the use of an ugly temporary, and know that your machine provides an efficient exchange instruction, convince your compiler vendor to recognize the standard three-assignment swap idiom in the optimization phase.

If you're consumed by a passionate desire to solve this problem once and for all, please reconsider; there are better problems worthier of your energies.

Additional links: so you think you have a solution


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North