d*******n 发帖数: 369 | 1 swap a and b using XOR (no the third variable). The following function is
correct? Explain
swap(int *a, int *b)
{
*a ^= *b ^= *a ^= *b;
}
I found that if I write it as follows, it's correct
*a ^= *b;
*b ^= *a;
*a ^= *b;
but *a ^= *b ^= *a ^= *b is wrong but why? explain in detail |
s*********t 发帖数: 1663 | 2 我试了试,第一种是对的啊
【在 d*******n 的大作中提到】 : swap a and b using XOR (no the third variable). The following function is : correct? Explain : swap(int *a, int *b) : { : *a ^= *b ^= *a ^= *b; : } : I found that if I write it as follows, it's correct : *a ^= *b; : *b ^= *a; : *a ^= *b;
|
d*******n 发帖数: 369 | 3 第一种是 a = 0 and b = 3;
【在 s*********t 的大作中提到】 : 我试了试,第一种是对的啊
|
w******e 发帖数: 81 | 4 看起来像是 *a^=*b^=*a^=*b在具体运算时第一个*a的值跟第二个*a的值没有同时
update。第一个*a应该是保留了初始值,第二个*a=*a^*b,之后*b换成*a的初始值,这
样最后一次*a^*b实际是两个相同的数xor,结果为0.
【在 d*******n 的大作中提到】 : 第一种是 a = 0 and b = 3;
|
i*****r 发帖数: 265 | 5 The statement is equivalent to *a = *a ^ (*b ^= *a ^= *b);
If compiler evaluates from left to right, then the second *a is the initial
value passed in, which is wrong. |