In C, when there are variables (suppose that as int ) i less than j , we can use the equation
i^=j^=i^=j
to exchange the values โโof two variables. For example, let int i = 3 , j = 5 ; after the calculated i^=j^=i^=j , I have i = 5 , j = 3 .
However, if I use two int pointers to redo this, *i^=*j^=*i^=*j using the example above, what I will have is i = 0 and j = 3 .
<h / "> In C
1
int i=3, j=5; i^=j^=i^=j;
2
int i = 3, j= 5; int *pi = &i, *pj = &j; *pi^=*pj^=*pi^=*pj;
In javascript
var i=3, j=5; i^=j^=i^=j;
JavaScript result makes it more interesting for me
my sample code is on ubuntu 11.0 server and gcc
#include <stdio.h> int main(){ int i=7, j=9; int *pi=&i, *pj=&j; i^=j^=i^=j; printf("i=%dj=%d\n", i, j); i=7, j=9; *pi^=*pj^=*pi^=*pj printf("i=%dj=%d\n", *pi, *pj); }
<h / ">
undefined behavior in c
Will undefined behavior in c be the real reason leading to this question?
1
the compiled code uses visual studio 2005 on Windows 7 to get the expected result (output i = 7, j = 9 twice).
2
compiled code using gcc on ubuntu ( gcc test.c ) produces an unexpected result (output i = 7, j = 9, then i = 0, j = 9)
3
the compiled code uses gcc on ubuntu ( gcc -O test.c ), gives the expected result (output i = 7, j = 9 twice).