0

I came upon this interview question through a link from LinkedIn and I know what an XOR does, but at the same time I am not comfortable with bit shifting and stuff like that, if I don't have to do it I try not to make things overly complicated for myself.

But I would really like to understand more about how these things work in the case that I find a good use case in the future.

Predict the output for the below program

public class Program
{
    public static void Main(string[] args)
    {
        int x = 1975;
        int y = 2015;
        x ^= y ^= x ^= y;
        Console.WriteLine("x = " + x + "; y = " + y);
    }
}

it gives the output

x = 0;Y=1975

Can someone please break this into steps to explain what exactly is going on in this line of code? order of assignment, etc?

x ^= y ^= x ^= y;
Malachi
  • 3,205
  • 4
  • 29
  • 46
  • 2
    I reopened the question, because the more interesting point here is not the xor, but the order of execution, meaning which values are actually xored. – René Vogt Aug 17 '16 at 14:29
  • 4
    I wouldn't be comfortable with such as interview question because of `x ^= y ^= x ^= y` being completely unreadable. A correct answer may indicate you are a nerd, but definitely not you are a good developer. – Ondrej Tucny Aug 17 '16 at 14:33
  • 2
    But could be treated as dupe of [Why does swapping values with XOR fail when using this compound form?](http://stackoverflow.com/q/5577140/15498) – Damien_The_Unbeliever Aug 17 '16 at 14:42
  • that is exactly what I was looking for @Damien_The_Unbeliever, thank you – Malachi Aug 17 '16 at 14:47

0 Answers0