Is there a built in swap function in C?

前端 未结 11 2169
北恋
北恋 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:42

    There is no standard function in C to swap two variables.

    A macro can be written this way:

    #define SWAP(T, a, b) do { T tmp = a; a = b; b = tmp; } while (0)
    

    and the macro can be called this way:

    int a = 42;
    int b = 2718;
    
    SWAP(int, a, b);
    

    Some solutions for a writing a SWAP macro should be avoided:

    #define SWAP(a, b) do { a = b + a; b = a - b; a = a - b; } while (0)
    

    when operands are of signed types an overflow can occur and signed overflow are undefined behavior.

    Also a solution trying to optimize the XOR solution like this should be avoid:

    #define SWAP(a, b) (a ^= b ^= a ^=b)
    

    a is modified twice between the previous and the next sequence point, so it violates the sequence points rules and is undefined behavior.

提交回复
热议问题