4

In Cprogramming.com I found this piece of code:

int a,b;
scanf("%d %d",&a,&b);
b=(a+b)-(a=b);
printf("%d %d",a,b);

It is claimed to be a tip/trick to "swap without using temporary". My tests on Linux gcc prove it. However, wouldn't the order how different compilers or platforms computing this expression matters here? Is it safe to use such code?

lastland
  • 890
  • 3
  • 14
  • 28

2 Answers2

12

No. In the expression (a+b)-(a=b) there is no sequence point between a being written to and a being read in the (a+b) sub-expression to determine the value to be stored to b so the behaviour is undefined.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • 1
    even if there were a sequence point, it still wouldn't be portable because of potential integer overflow; see also http://en.wikipedia.org/wiki/XOR_swap_algorithm#Variations – Christoph Feb 25 '12 at 16:49
8

However, wouldn't the order how different compilers or platforms computing this expression matters here?

Yes.

Is it safe to use such code?

No, it's undefined behavior.

sepp2k
  • 363,768
  • 54
  • 674
  • 675