Friday, August 29, 2014

Pre-increment Vs. Post-Increment, every programming student must know.

Most C/ C++ programmers are completely clear about the behavior of the ++ operator [and --] and the result of expressions that employs it. However, what if the return value is unused? Does it matter whether the code uses ++i or i++? This article looks at the finer points of compiler code generation and why that choice might matter.

Although any C programmer could easily learn another programming language and quickly become proficient in it, C continues to be the dominant language for embedded software programming. One reason for this is the large reservoir of expertise in the language, and most embedded C programmers understand the low-level nuts and bolts of the language. However, as embedded developers are always concerned with writing efficient code and minimizing overheads, being “proficient” is not enough.

There are still facets that may come as a surprise, even to those with years of experience.
A case in point is the pre-increment/post-increment problem. Not long ago, I was working on a conference paper about using C++ for embedded applications. I sent the paper out to the embedded compiler and programming language experts on the Mentor Embedded development tools team and asked them to review my work. As expected, I got some detailed and helpful feedback, but I was left wondering about one particular suggestion. I had written something like this:

  for (i=0; i<10; i++)
  ...

This seemed straightforward, but I was told that in terms of C++ style, it would be better to write this:
  for (i=0; i<10; ++i)
  ...


i++ and ++i

We are all familiar with the ++ operator (and its sibling --). Applying this operator increments the variable. Well, that is what appears to happen. Let’s look more closely.
++ is really a pair of operators: pre-increment and post-increment. The former increments the value of a variable and returns the resulting value; the latter increments the value of the variable and returns the value prior to the increment. So, if a variable x initially contains the value 3, the following expressions yield different results:

  y = ++x; // y==4, x==4
  y = x++; // y==3, x==4


The effect on x is the same in both cases, but y gets a different value.
This is all straightforward. The programmer needs to be careful to use the correct operator to achieve the required result in an expression.

No comments:

Post a Comment