Expert C Programming

(Jeff_L) #1

mango[i] = mango[i] + y; i++;


and not


mango[i++] = mango[i++] + y;


Once, when we were interviewing applicants for a position on Sun's Pascal compiler team, the best
candidate (and he ultimately got the job—Hi, Arindam!) explained these differences in terms of
compiler intermediate code, for example "++x" means take the location of x, increment the contents
there, put this value in a register; "x++" means take the location of x, load the contents into a register,
increment the value of x in memory, and so on. By the way, how would the other two statements be
described in compiler terms like these?


Though Kernighan and Ritchie say that incrementing is often more efficient than explicitly adding one
(K&R2, p. 18), contemporary compilers are by now usually good enough to make all methods equally
fast. Modern C compilers should compile these four statements into exactly the same code in the
absence of any surrounding context to bring out the differences. These should be the fastest
instructions for incrementing a variable. Try it with your favorite C compiler—it probably has an
option to produce an assembler listing. Set the compiler option for debugging, too, as that often makes
it easier to check the cor-respondence between assembler and C statements. Don't switch the optimizer
on, as the statements may be optimized out of existence. On Sun workstations, chant the magic
incantation "-S" so the command line will look like


cc -S -Xc banana.c


The -S causes the compilation to stop at the assembler phase, leaving the assembly language in file
banana.s. The latest compilers, SPARCompilers 3.0, have been improved to cause the source to
appear interspersed in the assembler output when this option is used. It makes it easier to troubleshoot
problems and diagnose code generation.


The -Xc tells the compiler to reject any non-ANSI C constructs. It's a good idea to always use this
option when writing new code, because it will help you attain maximum program portability.


So sometimes the difference is a question of what looks better in the source. Something short can be
simpler to read than something long. However, extreme brevity is also difficult to read (ask anyone
who has tried to amend someone else's APL code). When I was a graduate student teaching assistant
for a systems programming class, a student brought me some code that had an unknown bug in it, but
the code was so compressed that it could not be found. Amid jeers from some of the upperclassmen C
programmers, we methodically expanded one statement from something like:


frotz[--j + i++] += --y;


into the equivalent, but longer,:


--y;


--j;


frotz[j+i] = frotz[j+i] + y;


i++;

Free download pdf