Expert C Programming

(Jeff_L) #1

Convince yourself that the algorithm in the final answer above will detect a loop, if there is
one. Make a loop; dry run your code; make the loop longer; dry run again; repeat until the
induction condition jumps out at you. Also, convince yourself that the algorithm will
terminate if there is no loop.


Hint: write the program, and extrapolate from there.


What Are the Different C Increment Statements For?


Consider the four C statements below:


x = x+1; / regular /


++x; / pre-increment /


x++; / post-increment /


x += 1; / assignment operator /


Clearly, these four statements all do the same thing, namely, increase the value of x by one. As shown
here, with no surrounding context, there is no difference between any of them. Candidates need to
(implicitly or explicitly) supply the missing context in order to answer the question and distinguish
between the statements. Note that the first statement is the conventional way of expressing "add one to
x" in an algorithmic language. Hence, this is the reference statement, and we need to find unique
characteristics of the other three.


Most C programmers can immediately point out that ++x is a pre-increment that adds one to x before
using its value in some surrounding expression, whereas x++ is a post-increment that only bumps up x
after using its original value in the surrounding expression. Some people say that the "++" and "--"
operators were only put in C because *p++ is a single machine instruction on a PDP-11 (the machine
for which the first C compiler was written). Not so. The feature dates from the B language on the
PDP-7, but it turns out that the increment and decrement operators are incredibly useful on all
hardware.


Some programmers give up at this point, overlooking that x+=1 is useful when x is not a simple
variable, but an expression involving an array. If you have a complicated array reference, and you
want to demonstrate that the same index is used for both references, then


node[i >> 3] += ~(0x01 << (i & 0x7));


is the way to go. We took this example statement directly out of some


code in an operating system. Only the data names have been changed


to protect the guilty. A good candidate will also point out that the l-


value (compiler-talk for an expression that locates an object—usually


an address, but it may also be a register, or either of these plus a


bitfield) is only evaluated once. It makes a difference because the


statement


mango[i++] += y;


is treated as

Free download pdf