Frank's lil hideout ;>

Sunday, September 30, 2007

C++ versus C# behavior

Have you ever been wondering how subtle are the differences between those two major languages? I’ve been checking why += operator isn’t overloadable in C# and I've found out one language-hidden detail which led me to the original concept of this language and what lack of += operator is causing.

Look at this example:

int z = 1;
int x = (z += 2) + (z += 3);

and now tell me x == ?

Regarding to the C# the answer is 9 and as for C++ x == 12 …

What?! How the hell it is possible to create two different results for such simple operations using similar languages and more importantly one of them being descendant of the other?!

Answer is very easy -> lack of overloadable += operator in C# which lead to the main concept – implicit, reference driven assignments in C#.

Stop at this point, try to think a little and say… which approach is more logical? You say C#ish? Yea, you’re right, at least for now… in fact there is no right answer. Let’s look more closely:

C++ approach:

z = 1;
x=(z+=2) + (z+=3);
z+=2 -> z==3
z+=3 -> z==6
z+z -> 12

C#ish:

z = 1;
x=(z+=2) + (z+=3);
z+=2 -> z==3
z+=3 -> z==6
3+6 -> 9

As you can see – C# is not using direct reference, but instead it’s storing temporary value created by a previous expression! Really? Not necessarily.

Behind the C++ scene

class foo {
int x;
public:
foo() { x = 1; }
foo& operator += (int val) { x += val; return *this; }
int operator + (foo& b) { return x + b.x; }
};

Let’s do an explicit derivation.

int z = a.operator + (a.operator += (2), a.operator += (3));
" a.operator += (2)" -> a.x == 3 ATP, returning reference to „a”
" a.operator += (3)" -> a.x == 6 ATP, returning reference to „a”
“a.operator + (reference_to_a, reference_to_a)” -> returning 12!

So what C# is doing differently? Let me show…

Behind C# scene

class foo {
int z = 1;
public static foo operator +(foo a, int b) { foo result = new foo(); result.z = a.z + b; return result; }
public static int operator +(foo a, foo b) { return a.z + b.z; }
}

Without getting into details this time, C# is enforcing to use additional + operator instead of += and to create a new instance because + operator should not modify internals of its arguments.

What if I want to modify them? Well no one is stopping you and in fact it will lead to the “twelve” as a result but… this is enforcing programmer to differentiate usage of such simple operator + to act like += operator in this case which leads to confusion.

Till now I thought C# is more clear but I think I have to restate my assumptions :)

1 Comments:

  • http://wojtekobst.blogspot.com/2007/10/linki-31102007.html

    By Blogger Wojtek, at 9:13 PM  

Post a Comment

<< Home