Undefined behavior and other delights of (bad) C programming

I started a couple of weeks ago, when I received an email from Sandeep Vasant from Ahmedabad University in India. For reasons that he has yet to reveal, he was having trouble with some code like this:

int a=10, b=20, c=0; c = a++ + a++ + b++ + b++ + ++a + ++b; 

He tried this with one compiler and the resulting values of a, b and c were 13, 23 and 96 respectively. He was satisfied with this result. Then he tried a different compiler, which yielded a final value for c of 98, which he found confusing.

I started looking into this, certain that the explanation was simple …

As I work for a company that sell embedded software development tools, I have a natural interest in programming languages and their quirks – even if the code is not specifically embedded. I believe that embedded developers are often more interested in what is going on “behind the scenes” than their desktop computer software development counterparts.

My first thought was that, although the precedence of the +and ++ operators is clear and the functionality of the pre-increment and post-increment versions of ++ is unambiguous, the order of evaluation of the the operators is not defined. Maybe they are evaluated left to right or perhaps right to left. So, instead of using a compiler, I decided to work it out by hand. Going left to right, I got 10 + 11 + 20 + 21 + 13 + 23 = 98; going the other way, I got 21 + 11 + 21 + 22 + 11 + 12 = 98. So it made no difference. In both cases I got the result that Sandeep had been confused by.

Now it was time to try a compiler [I used CodePad]. I wrote this:

To read the rest of this entry, visit the Colin Walls blog on Mentor Embedded.