Thursday, February 20, 2014

Demonstrable bug in C#

I've found a demonstrable bug in C# regarding at least the boolean XOR operator.


Consider the following code:



int i = 381;
int j = 529;
j ^= i ^= j;
i ^= j;
Console.WriteLine("i=" + i.ToString() + "; j=" + j.ToString());



This works: it swaps the values of i and j; the output reads "i=529; j=381"


Logically, you should be able to write this as:



int i = 381;
int j = 529;
i ^= (j ^= i ^= j);
Console.WriteLine("i=" + i.ToString() + "; j=" + j.ToString());



...but you can't. If you do, the output reads, "i=0; j=381".


In C, this works - even as i^=j^=i^=j; -- there's definitely something not quite right with the way C# is evaluating inline expressions. I've also tried i^=(j^=(i^=j)); -- that doesn't work either - and I also switched off code optimization, to no effect.


Comments?


No comments:

Post a Comment