Is there a built in swap function in C?

前端 未结 11 2088
北恋
北恋 2020-12-15 16:01

Is there any built in swap function in C which works without using a third variable?

11条回答
  •  有刺的猬
    2020-12-15 16:35

    there is std::swap since in general it depends on your processor, whether it supports swaping. there is an instruction called "compare and swap", but it only works on types that fit into a register and is guaranteed to be atomic. There is a built-in implementation of compare and swap (CAS) from gcc it's used for synchronization of thread and mutex implementations and probably way out of scope for your purpose so it's best to stick with just using a temporary variable or if you are really stuck to C you can always use a macro like this:

    #define swap(a,b) a=a^b; \
                      b=a^b; \
                      a=b^a;
    

提交回复
热议问题