Tech Journal Back to Tech Journal

C Riddle: Multiple preincrement in a single line give unexpected results...

Have a look at this piece of code:

x = 0
i = (++x) + (++x) + (++x)

What we get is: i == 7 Why?

Here's a clue: The following code results in i == 4

x = 0
i = (++x) + (++x)

Since the + operation is communitive, it allows the compiler the freedom to generate code for each side of the + in what ever order it pleases. So if we has something like i = (++x) + (++x) then the compiler may evaluate both sides in either order, so it first sees ++x, so x=1, and then it sees the other ++x, so x=2, then it adds x+x (since ++x after doing the ++ becomes "x" which is "get the value of x") and gets 2+2=4.

Same way for i = (++x) + (++x) + (++x), the first part gives 4, like the previous example, and then the next (++x) is evaluated, causing x=3, and therefore we get i = 2 + 2 + 3 = 7

for something like i = (++x) + (++x) + (++x) + (++x) the results may be even more questionable! Since the compiler can do + in any order, it is allowed to do a+b+c+d as (((a+b)+c)+d) or ((a+b)+(c+d)) which can result in either of these:

i = 2 + 2 + 3 + 4 = 11
i = 2 + 2 + 4 + 4 = 12

(Note from Shalom: not sure the 2nd option is possible)

Last updated on 2005-08-02 14:00:00 -0800, by Shalom Craimer

Back to Tech Journal