wolfgang ziegler


„make stuff and blog about it“

x = x++

August 28, 2008

Today I had to analyze a hang in our software, which had been introduced during the last few builds. I soon figured out, that this hang was caused by an infinite while loop. Looking for the cause of the infinite run of the loop, I encountered this strange instruction: x = x++ This statement was probably meant to increase the control variable of the while loop, but stepping through the code with the debugger I noticed that the value of x did not change at all!

Strange at first glance but quite obvious considering the behavior of the post-increment operation.

Assuming x has a value of 42 – that’s what happens if x = x++ is executed:

  1. The right part of the expression evaluates to 42 since we deal with a post-increment operation.
  2. Then the actual increment happens and x is incremented to 43.
  3. Now x gets assigned the result of the first step, which is – yes, you already guessed it – 42.

Even though – for a really short amount of time – x is incremented, it gets overwritten with its original value, which is the result of the post-increment operation.

Apparently the programmer’s intention was to increase x, but he produced a very well-disguised NOP operation, which even made it through code-review process.