Assignment chaining - differences between C# and C++

  • Thread starter Thread starter Aaron Garth Enright
  • Start date Start date
A

Aaron Garth Enright

Guest
I was trying to give a programming problem to an interviewee at my company and I dug out one of my old C++ problems. It's intentionally obscure and meant to see if the candidate could read bad code, but I did not expect the code to not work when translated to C#. The C++ code swaps two values using XOR, and it a pretty simple snippet:

#include "pch.h"
#include <iostream>

int main()
{
int a = 3;
int b = 8;

a ^= b ^= a ^= b;
std::cout << "a=" << a << " b=" << b;
getchar();

return 0;
}

The code spits out "a=8 b=3" as expected. However, if I translate this to C#:

using System;

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int a = 3;
int b = 8;

a ^= b ^= a ^= b;
Console.WriteLine($"a = {a} b = {b}");
Console.ReadKey();
}
}
}


The code spits out "a=0 b=3", which is different than the C++. Interestingly enough, if I remove the assignment chaining, and break it into 3 assignments as below:

using System;

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int a = 3;
int b = 8;

a ^= b;
b ^= a;
a ^= b;

Console.WriteLine($"a = {a} b = {b}");
Console.ReadKey();
}
}
}


Now I get the "a=8 b=3" that I expected. So, my question is does assignment chaining have different semantics in C# than it does in C++?

Continue reading...
 
Back
Top