01.Blogs :
RobMiles  
Programming, gadgets and life as a lecturer in a UK university.

Puzzle Thursday

Consider the following C# code:

x = 1 ;
y = x + x + x ;

..but at the end of it the variable y has the value 9 in it. How come?

posted on Thursday, June 17, 2004 8:54 AM by RobMiles

# @ Thursday, June 17, 2004 2:51 PM

ah, well, you haven't told us what x and y are. If we assume they are integers than y will have the value 3. But if they are some other sort of object with a different overloading of + that could make a lot of difference.

AlfredTwo

# @ Thursday, June 17, 2004 2:52 PM

OK. x and y both hold integers. And I've not overloaded the + operator (I don't like overloading). And you can only do this in C# (although you'd be mad to!)

RobMiles

# @ Friday, June 18, 2004 7:45 AM

Hmm. Close. There is nothing special about y though. However, x is not all it seems...

RobMiles

# @ Tuesday, June 22, 2004 3:12 PM

We have a winner! But there is no prize. If you are ever in Hull I'll buy you a pint. The code illustrates neatly the problems with side effects. And with properties it is even more dangerous, because a reader of the code wil not be able to figure out that code is being executed. You can use this for primitive profiling, if you want to find out how often a variable is used you can make it into a property for a while and have it update a counter each time it is read. You can also use it to give you breakpoints when a variable is accessed - particularly useful if something is corrupting a variable and you don't know where from. (although I think Visual Studio will do this anyway but I've not looked)

RobMiles


 
03.UPDATE CALENDAR :
<June 2004>
SunMonTueWedThuFriSat
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

05.MY LINKS :

07.Subscriptions :

Subscriptions


© Copyright 2005 Microsoft Corporation. All Rights Reserved.
Terms of Use | Privacy Statement | Code of Conduct | Hosted by MaximumASP for Microsoft
WHO-BAR