JeffMc's Technical Blog

Where I talk about code and methods

Bad C Coding

Back 20 Years ago, I had the job of moving Microsoft’s Windows NT operating system to the Digital Equipment Corp’s Alpha processor. During this project, one of the things I found out is how bad some people code in C, and the effects that has using compilers you have no control over.

Lets look at an example:

            for (int i = 0; i < MAX_TABLE_SIZE; i++) {

                *s++ = &s[i];


What does this do? Well the attempt by someone in the Win32 layer was to initialize a table. Now, as long as the code was compiled with the MS C compiler, it worked. But, using the DEC supplied strict ANSI-C compiler (it was initially DEC’s Alpha Unix 64bit compiler with a 32bit address mode.), the results were bad. This is due to using the variable “s” on both sides of the expression, and altering such variable at some point.

The “Bible of C” “The C Programming Language” by Dennis Ritchie and Brian Kernighan states on page 200, Appendix A (second edition of the book):

“The precedence and associativity of operators is fully specified, but the order of evaluation of expression is, with certain exceptions, undefined, even if the subexpression involve side effects. That is, unless the definition of an operators guarantees that its operands are evaluated in a particular order, the implementation is free to evaluate operands in ANY order or even to interleave their evaluation.”

So, given the above statement, what is the precedence? Do we provide the address of s[i], or do we use &s and then use the index? Do we auto increment s, before we do &s[i]?

As you can see, it is dependent on compiler. Nowadays, there is either gcc, clang or MSVC. But back in those days, we had 2 compilers on three different architectures. i386 and MIPS used MSVC and Alpha used DEC’s ANSI-c compiler. i386 and MIPS were 32 bit machines, and Alpha was a 64 bit machine (with canonical 32bit pointer support).

I ask when i am interviewing someone if they can see the error in the above statement, and they simply say nothing is wrong. While with today’s compilers, it “might” work, one still has to say it is bad C code.