8/16/12

Curious look into code evaluation

If you have been programming for a while, you already should know about operator precedence. If you for some reason don't, now is a good time to read about it on from Wikipedia or the documentation of your language of choice.

Before proceeding, remember that this may contain some erroneous information, and if you notice any, please inform me so that article can be fixed.

Let's take a rather simple set of expressions:

int i = 5; 
i = ++i + ++i;

This seems rather simple, doesn't it? So did I think, but the results (which we'll see a bit late) left me thinking wtf was actually going on. If we look at the Wikipedia-article, we can see that unary operators such as prefix and suffix increment and decrement come before the addition and substraction, at least in C-family of languages. Now, what do you think the answer will be? Write your guess down somewhere, we'll take a small plunge in to the world of compilers soon.

So, you got your answer? Good. If you did a quick test with a short code of piece, shame on you. Now, let me guess what you got.

If you used Python or Ruby, you got 10.
If you used JS, Java or C#, you got 13.
If you used C, C++ or Perl, you got 14.

Wait, what? How does this even happen?