1

Can someone explain how exactly this works step by step (how in the end y becomes x and x becomes y)?

#include <iostream>
using namespace std;

int main()
{
    int x, y;
    x = 2; y = 3;

    x ^= y ^= x ^= y; // <- how this line exactly works?

    cout << x << ' ' << y << endl; //returns: 3 2
    system("pause");
}
  • I used this code with Visual Studio 2015 Update 1
BlueMark
  • 962
  • 4
  • 23
  • 41
  • 3
    It doesn't work - it exhibits undefined behavior. It may or may not seem to work. – Igor Tandetnik Jan 23 '17 at 02:24
  • 1
    Which part of it needs explanation? Do you know what `int` does? ` And `^=`? and `;`? Be more specific about what you thought this would do and what confuses you, and where you got stuck when you researched each of the blocking points. – Kerrek SB Jan 23 '17 at 02:27
  • `x ^= y ^= x ^= y ;` -> this part – BlueMark Jan 23 '17 at 02:28
  • @IgorTandetnik It's legal and works as of C++11. Still shitty code though of course. – Baum mit Augen Jan 23 '17 at 02:31
  • @BaummitAugen: Do you have a source for that? The answer here claims otherwise, and supports it with citations from the C++11 standard: http://stackoverflow.com/questions/28782068/undefined-behaviour-of-operators-in-xor-swap-algorithm – Dietrich Epp Jan 23 '17 at 02:34
  • @BaummitAugen I'm 99% sure this is UB. It's equivalent to `x = x ^ (y ^= x ^= y)` (**[expr.ass]/7**), whereupon you have a value computation of `x` unsequenced with a side effect modifying `x` (UB per **[intro.execution]/15**) – Igor Tandetnik Jan 23 '17 at 02:36
  • Hm, I'm probably wrong. Gotta double check. – Baum mit Augen Jan 23 '17 at 02:41
  • @BaummitAugen You might be thinking of pre-increment and pre-decrement - those are "more defined" in C++11 than they were in C++98. `x = ++x;` used to be undefined, but is now well-defined. – Igor Tandetnik Jan 23 '17 at 02:46
  • Looks like I was just wrong. Sorry. – Baum mit Augen Jan 23 '17 at 02:52
  • @DietrichEpp that answer concludes with "UNSPECIFIED/UNDEFINED RESULT" - which is not a real thing; it's either undefined behaviour or it isn't – M.M Jan 23 '17 at 08:13
  • @M.M: That's a pretty narrow reading. Sure, the answer isn't written as precisely as the language standard itself, but it's clear what it means in context. – Dietrich Epp Jan 23 '17 at 15:59
  • @DietrichEpp it's not clear to me. Undefined behaviour can launch missiles (or have any other nasty side-effect), whereas unspecified behaviour will, at worst, end up with an unintended value stored in the variables – M.M Jan 24 '17 at 08:11
  • @M.M: Perhaps what I meant to say is that you can figure out what the correct answer is from that answer. Even though the answer uses imprecise language in its conclusion, from the citations and logic leading to the conclusion, it's clear that the behavior is undefined. – Dietrich Epp Jan 24 '17 at 09:57

0 Answers0