Magic in C ++ with this expression x = y - x + (y = x)

In Python, you can easily exchange the values โ€‹โ€‹of two variables with the following expression:

x, y = y, x

      

In C ++, on the other hand, if you want to swap the values โ€‹โ€‹of two variables, you usually use a temporary variable to store the value of one of your variables, something like this:

int var1 = 100;
int var2 = 200;

int temp = var1;
var1 = var2;
var2 = temp;

      

It's easy, but you have to write a lot of code.

The professor I follow his lectures on C ++ discovered a new compact way to exchange the values โ€‹โ€‹of two variables in a magical way:

int x = 200;
int y = 100;

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

      

It seems incredible, but it works with both the compiler in use and mine Apple LLVM version 6.0 (clang-600.0.56)

.

It looks like the interpreted expression looks like this:

  • (y = x) // returns x
  • -x + x = 0
  • x = y + 0
  • x = y
  • y = x // finally y gets the initial value of x

, :

for (int i = -10; i <= 10; i++) {
    for (int j = 10; j >= -10; j--) {
        int x = i, y = j;
        x = y - x + (y = x);

        std::cout << "x = " << x << "\ny = " << y << '\n';
    }
}

      

, , :

main.cpp: 28: 22: : 'y' [-Wunsequenced]

, , 2 , .

++ ?

+3




3


undefined, . . , y

y = x

.



The reason this is stated is to provide flexibility for optimization.

+9


source


It "works" because you're out of luck.

Yes, I said I was out of luck. The code has undefined behavior; the fact that it appears to "work" means that your compiler let you get away with code that might fail the next time you run it.

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

      



The object y

is accessed twice, once to read its value, and once to assign a value to it. Language does not dictate the order in which these calls occur, or that they occur in any order at all. As the warning message says, they are "not affected". Possible behavior is not limited to two possible orders; the behavior is completely undefined.

Also, addition and / or subtraction can overflow, which is another potential source of undefined behavior.

+6


source


These are: `x = y - x + (y = x); - undefined behavior in C - 1 undefined behavior as specified in the C99 spec:

Between two points in the sequence, the object is modified more than once or changed, and the previous value is read differently than to determine the value to store

The only sequence points in this expression are the beginning of the expression and the end of the complete expression.

+2


source







All Articles