Interesting snippet

August 28th, 2006

Ayende has posted an interesting code snippet useful to measure how much a candidate to a job knows about the compiler he/she claims to work on.

selected = selected++;

I’ve seen this one years ago (2002 I think) in a Java prep exam. My first guess was that ‘selected’ variable would hold the result of selected++. Wrong! Then I kind memorized that this one was tricky, but forgot why. But today I was curious enough to check again the IL code to see where is the trick.

The C# code

selected = 1;
selected = selected++;

The IL

L_0000: ldc.i4.1 // loads the literal 1
L_0001: stloc.0  // store in the local
L_0002: ldloc.0 // load the local value (1)
L_0003: dup  // duplicates the stack, now we have two ints with value 1
L_0004: ldc.i4.1 // loads the literal 1 (++)
L_0005: add // sum 1 + 1 and push the result on the stack (2)
L_0006: stloc.0 // saves the value 2 on the local variable which is the top level item on the stack
L_0007: stloc.0 // whoops, the int on the stack now is the 1, store it (overriding the result of the increment)

Knowing this kind of behavior might be useful. On the project I was working on I coded something like the following

int val = 1;
string something = "some value " + (val + ',' + "something else");

Can you the headache this gave me?

If you have time and likes to read, the book Programming language pragmatics is a gem.

Categories: Fun, General | Top Of Page | 8 Comments » |

8 Responses to “Interesting snippet”

Ayende Rahien Says:

Maybe I missed something, but what is wrong with the last snippet?

The order of eval is something like:

val +’,’ == ’1,’
+ “something else” == ’1,something else”
“some value ” + == “some value 1,something else”

Unless I really missed the boat on that one.

hammett Says:

Did you test it? :-)

val + ’,’ == 45 (IIRC). It sums the int with a char. It was an easy fix though: val.ToString() + ’,’

Andrew Hallock Says:

Is that what the behavior should be, though? Placing the ++ operator after the variable means you want it to take effect after the current statement (which is questionable in itself because of code clarity). So, in this case, the variable is assigned to itself and then incremented, resulting in 2.

Jeez, I can’t believe I got all fired up over selected = selected++ :)

hammett Says:

Andrew, that’s the tricky part. :-)

Ayende Rahien Says:

Hammett, didn’t even notice the single quote, damn!

Brenton House Says:

Interesting interview question

Hamilton Verissimo posts details about an interesting interview questions Interesting snippet Via Zen

Eber Irigoyen Says:

I’ve been bitten by this before

RedGreenRefactor Says:

I know i’m verrrry late but the basic things always keep actual. The following is something alike.

x = 1;
x = (++x) + x;

Leave a Reply