Search code examples
cexpressionoperator-precedencesequence-points

Swapping the values of two variables without using third variable in C?


I've found the following code snippet:

#include <stdio.h>

int main(void) {
    int x=10,y=15;
    x=x+y-(y=x);
    printf("x=%d y=%d",x,y);
    return 0;
}

It actually swaps the variables

Can anybody explain me how the the code swaps the variable?

I thought the bracket would execute first and then expression leads to

x=x+y-y;

Solution

  • This algorithm does not work because it invokes undefined behavior on this line:

    x=x+y-(y=x);
        ^  ^
    

    You are modifying y and also using its value within the same sequence point as per section 6.5 of the draft C99 standard:

    Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.72) Furthermore, the prior value shall be read only to determine the value to be stored.73)

    There is also the matter of unspecified behavior since the order of evaluation of the sub-expressions is unspecified:

    The grouping of operators and operands is indicated by the syntax.74) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.

    In this case if you were using clang it would have provided the following warning:

    warning: unsequenced modification and access to 'y' [-Wunsequenced]
    x=x+y-(y=x);
        ~   ^
    

    as far as I can tell by default. You can receive a similar warning from gcc by using -Wall.

    There are several SO questions that cover how to swap without a temporary for example Swapping two variable value without using 3rd variable.