Is there a built-in way to swap two variables in C

后端 未结 10 1553
夕颜
夕颜 2020-12-01 14:53

I know how to swap 2 variables in c++ , ie you use std::swap(a,b).

question:

Does the C standard library have a similar function

10条回答
  •  伪装坚强ぢ
    2020-12-01 15:16

    In C this is often done using a macro,
    there are very simplistic examples, eg:
    #define SWAP(type,a,b) {type _tmp=a;a=b;b=_tmp;}
    ... but I wouldn't recommend using them because they have some non-obvious flaws.

    This is a macro written to avoid accidental errors.

    #define SWAP(type, a_, b_) \
    do { \
        struct { type *a; type *b; type t; } SWAP; \
        SWAP.a  = &(a_); \
        SWAP.b  = &(b_); \
        SWAP.t  = *SWAP.a; \
        *SWAP.a = *SWAP.b; \
        *SWAP.b =  SWAP.t; \
    } while (0)
    
    • Each argument is instantiated only once,
      so SWAP(a[i++], b[j++]) doesn't give problem side effects.
    • temp variable name is also SWAP, so as not to cause bugs if a different name happens to collide with the hard-coded name chosen.
    • It doesn't call memcpy (which in fact ended up doing real function calls in my tests, even though a compiler may optimize them out).
    • Its type-checked
      (comparing as pointers makes the compiler warn if they don't match).

提交回复
热议问题