简体   繁体   中英

using pointers and “^=” to swap values

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 ^= *pb doesn'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.

Before answering your question I would like to introduce:

Sequence point :

A sequence point is a point in time at which the dust has settled and all side effects which have been seen so far are guaranteed to be complete.

The Standard states that:

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.

Now, your problem is that, in the expressions

a ^= b ^= a ^= b;  

and

 *pa ^= *pb ^= *pa ^= *pb;  

There is only one sequence point ; (at the end of expressions) and you are modifying a twice in first expression and *pa in second expression between two sequence point (previous ; and the ; at the end of these expressions here) which causes the behavior of program undefined .

Further reading: comp.lang.c FAQ list · Question 3.8 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM