Sequence Point - Xor Swap on Array get wrong result

后端 未结 1 556
挽巷
挽巷 2020-12-22 11:16

I learned using Xor operator to swap two integers,like:
int a = 21;
int b = 7;
a^=b^=a^=b;

I would finally get a=7 and b=21.

I try

相关标签:
1条回答
  • 2020-12-22 12:04

    You cannot modify a variable more than once without an intervening sequence point, if you do so, it is Undefined Behavior.

    a^=b^=a^=b;
    

    Trying to modify the values of a and b in the above statement breaks this rule and you end up with an Undefined Behavior.
    Note that Undefined Behavior means that any behavior is possible and you can get any output.

    Good Reads:

    • Undefined Behavior and Sequence Points
    • C-Faq
    0 讨论(0)
提交回复
热议问题