I stumbled into this code for swapping two integers without using a temporary variable or the use of bitwise operators.
int main(){
int a=2,b=3;
printf("a=%d,b=%d",a,b);
a=(a+b)-(b=a);
printf("\na=%d,b=%d",a,b);
return 0;
}
But I think this code has undefined behavior in the swap statement a = (a+b) - (b=a); as it does not contain any sequence points to determine the order of evaluation.
My question is: Is this an acceptable solution to swap two integers?
No. This is not acceptable. This code invokes Undefined behavior. This is because of the operation on
bis not defined. In the expressionit is not certain whether
bgets modified first or its value gets used in the expression (a+b) because of the lack of the sequence point.See what standard syas:
C11: 6.5 Expressions:
Read C-faq- 3.8 and this answer for more detailed explanation of sequence point and undefined behavior.
1. Emphasis is mine.