Interesting interview question

Hamilton Verissimo posts details about an interesting interview questions  
 
Via Zen and the art of Castle maintenance -

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.

 

Recent Posts

Tag Cloud

1 Comment

Comments have been disabled for this content.