Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using pointers and "^=" to swap values

Tags:

c

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?

like image 989
user2990911 Avatar asked Feb 27 '26 09:02

user2990911


2 Answers

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.

like image 91
David Heffernan Avatar answered Mar 01 '26 23:03

David Heffernan


You need an intervening sequence point. Otherwise, this is undefined behavior.

like image 30
David Schwartz Avatar answered Mar 01 '26 23:03

David Schwartz