Interview Question, i = (i++) + i + (++i) explained at a low level

int x = 5; 
x = (x++) + x + (++x);

This piece of code might come up as a Interview question

and you might ever so kindly thank the interviewers for their time and take a dash for the nearest exit because indeed the code looks as hard to understand as it is to read even though it’s a simple expression.

If you break down the calculation to tiny segments you may come up with the answers 16, 17, 18, 19 or something else, Many programmers will see and instantly recognise x++ as the increment number expression and then look on and see ++x, an expression which looks as foreign as can be. If we break down the issue it will become quite clear, lets first recap what you may already know.

x++ – Increment x by 1, the value before incrementing is returned, This can be cancelled out in cases like x := x++; this means that if x=5, x := (x++), the result will x := x,  x++ would set x to 6 but then x = RESULT will initiate and set x to the result which is x before the increment (5), to combat this if you are using x++ by itself you would have it by itself. A good example of this is in loops for (int x = 0; x < 5; x++).

++x – Increment x by 1, the value after incrementing is returned. This means that x := ++x or x := x + 1 where x=5, ++x will return 6 for the expression.

 

Lets take a look at the question again

int x = 5; 
x = (x++) + x + (++x);

Continue reading “Interview Question, i = (i++) + i + (++i) explained at a low level”