why i^=j^=i^=j isn't equal to *i^=*j^=*i^=*j

In C, when there are variables (assume both as int) i less than j, we can use the equation

i^=j^=i^=j

to exchange the value of the two variables. For example, let int i = 3, j = 5; after computed i^=j^=i^=j, I have i = 5, j = 3.

However, if I use two int pointers to re-do this, with *i^=*j^=*i^=*j, using the example above, what I have will be i = 0 and j = 3.


In C

1
    int i=3, j=5;
    i^=j^=i^=j; // after this i = 5, j=3
2
    int i = 3, j= 5;
    int *pi = &i, *pj = &j;
    *pi^=*pj^=*pi^=*pj; // after this, $pi = 0, *pj = 5

In JavaScript

    var i=3, j=5;
    i^=j^=i^=j; // after this, i = 0, j= 3

the result in JavaScript makes this more interesting to me

my sample code , on ubuntu server 11.0 & gcc

    #include <stdio.h>
    int main(){
        int i=7, j=9;
        int *pi=&i, *pj=&j;
        i^=j^=i^=j;
        printf("i=%d j=%d\n", i, j);
        i=7, j=9;
        *pi^=*pj^=*pi^=*pj
        printf("i=%d j=%d\n", *pi, *pj);
    }


undefined behavior in c

Will the undefined behavior in c be the real reason leads to this question?

1

code compiled use visual studio 2005 on windows 7 produce the expected result ( Output i = 7, j = 9 twice.)

2

code compiled use gcc on ubuntu ( gcc test.c ) produce the unexpected result ( Output i = 7, j = 9 then i = 0, j = 9 )

3

code compiled use gcc on ubuntu ( gcc -O test.c ) produce the expected result ( Output i = 7,j = 9 twice. )

Answers


i^=j^=i^=j is undefined behavior in C.

You are violating sequence points rules by modifying i two times between two sequence points.

It means the implementation is free to assign any value or even make your program crash.

For the same reason, *i^=*j^=*i^=*j is also undefined behavior.

(C99, 6.5p2) "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression."


Need Your Help

How to remove black edge on UIImageView with rounded corners and a border width?

ios objective-c uiimageview quartz-graphics

I have the following code to make the UIImageView in each of my UITableView's cells have rounded corners:

XXX on output ports

verilog hdl xilinx-ise

I have written an asynchronous fifo buffer but when I run it I get XXX on output ports. I referred to concerned questions on SO which said asserting reset signals should make it work but despite of...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.