Swapping variables.

来源:互联网 发布:淘宝空间协议 编辑:程序博客网 时间:2024/06/05 17:04

http://www.azillionmonkeys.com/qed/case3.html

 

 

#define swap(a,b) { /
        (a) ^= (b);     /
        (b) ^= (a);     /
        (a) ^= (b);     /
    }

 

#define swap(a,b) {  /
        (a) += (b);      /
        (b) = (a) - (b); /
        (a) -= (b);      /
    }

 

 

More slick expression

#define swap(a,b) { a ^= b ^= a ^= b; }


But here
http://c-faq.com/cpp/swapmacro.html.

It seems it is not a good way to use a macro .

------------------------------------------------------------------------------------------------------------------------------------------------
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:
  • It's hard to givethe temporarya name that won't clash with anything.(Any name you pickmight be the actual name of one of the variables being swapped.If you triedusing ##to concatenate the names of the two actual arguments,to ensure that it won't match either one,it might still not be uniqueif the concatenated name is longer than 31 characters,[footnote]and itwouldn't let you swap things like a[i] that aren't simple identifiers.You could probably get away with using a name like _tmp in the ``no man's land'' between the user and implementation namespaces; see question 1.29.)
  • Either it can't be declared with the right type(because standard C does not provide a typeof operator),or(if it copies objects byte-by-byte,perhaps with memcpy,to a temporary array sized with sizeof)the macro can't be used on operands which are declared register.

The best all-around solution is probably to forget about using amacro,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 toexchange pointersinstead.)If you're worried about the use of an ugly temporary, and knowthat your machine provides an efficient exchange instruction, convince yourcompiler vendor to recognize the standard three-assignment swapidiom in the optimization phase.

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