XOR Swapping output prediction
#include <stdi开发者_Python百科o.h>
void fun(char a[]){
a[0]^=a[1]^=a[0]^=a[1];
}
int main(int argc, char **argv){
char b[10];
b[0]='h';
b[1]='j';
fun(b);
printf("%c",b[0]);
return 0;
}
What is wrong with this code. It shall swap the b[0]
and b[1]
but it is not swapping.
Undefined behavior for a[0]^=a[1]^=a[0]^=a[1];
. Order of evaluation and assignment is not defined.
The "The New C Standard. An Economic and Cultural Commentary" book gives two variants of xor-swap at page 1104:
Example
1 #define SWAP(x, y) (x=(x ^ y), y=(x ^ y), x=(x ^ y))
2 #define UNDEFINED_SWAP(x, y) (x ^= y ^= x ^= y)
/* Requires right to left evaluation. */
So, the second variant is not portable and is incorrect.
精彩评论