How to swap two numbers without using temp variables or arithmetic operations?

后端 未结 10 1024
Happy的楠姐
Happy的楠姐 2020-12-13 00:09

This equation swaps two numbers without a temporary variable, but uses arithmetic operations:

a = (a+b) - (b=a);

How can I do it without ar

10条回答
  •  醉话见心
    2020-12-13 00:45

    Using XOR,

    void swap(int &a, int &b)
    {
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;
    }
    

    One liner with XOR,

    void swap(int &a, int &b)
    {
        a ^= b ^= a ^= b;
    }
    

    These methods appear to be clean, because they don't fail for any test-case, but again since (as in method 2) value of variable is modified twice within the same sequence point, it is said to be having undefined behavior declared by ANSI C.

提交回复
热议问题