Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would it be safe to do swap by "b=(a+b)-(a=b);"?

Tags:

c

c99

c89

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?

like image 738
lastland Avatar asked Nov 30 '22 06:11

lastland


1 Answers

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.

like image 87
CB Bailey Avatar answered Dec 05 '22 02:12

CB Bailey