I try to swap values by using ^= (i know it is better to use another variable to do this), but the result isn't correct.
#include <stdio.h>
int main() {
int a = 3, b = 5, *pa = &a, **ppa = &pa, *pb = &b, **ppb = &pb;
*pa ^= *pb;
*pb ^= *pa;
*pa ^= *pb;
printf("pointer 1: a = %d, b = %d\n", a, b);
a ^= b ^= a ^= b;
printf("variables: a = %d, b = %d\n", a, b);
*pa ^= *pb ^= *pa ^= *pb;
printf("pointer 2: a = %d, b = %d\n", a, b);
return 0;
}
The result is
pointer 1: a = 5, b = 3
variables: a = 3, b = 5
pointer 2: a = 0, b = 3
I want to know why *pa ^= *pb ^= *pa ^= *pbdoesn't work properly. Can any one tell me?
There is no sequence point between the assignments in
*pa ^= *pb ^= *pa ^= *pb;
So the behaviour is not defined.
Neither is there a sequence point between the assignments in
a ^= b ^= a ^= b;
So the behaviour of that line is also undefined. If that happened to work then you were (un)lucky.
You need an intervening sequence point. Otherwise, this is undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With