user302520
user302520

Reputation:

XOR Swapping output prediction

#include <stdio.h>

void fun(char a[]){

  a[0]^=a[1]^=a[0]^=a[1];

}

int main(int argc, char **argv){

  char b[10];
  b[0]='h';
  b[1]='j';
  fun(b);
  printf("%c",b[0]);

  return 0;
}

What is wrong with this code. It shall swap the b[0] and b[1] but it is not swapping.

Upvotes: 2

Views: 340

Answers (2)

osgx
osgx

Reputation: 94235

The "The New C Standard. An Economic and Cultural Commentary" book gives two variants of xor-swap at page 1104:

Example
1 #define SWAP(x, y) (x=(x ^ y), y=(x ^ y), x=(x ^ y))

2 #define UNDEFINED_SWAP(x, y) (x ^= y ^= x ^= y) 
     /* Requires right to left evaluation. */

So, the second variant is not portable and is incorrect.

Upvotes: 3

MByD
MByD

Reputation: 137322

Undefined behavior for a[0]^=a[1]^=a[0]^=a[1];. Order of evaluation and assignment is not defined.

Upvotes: 11

Related Questions