Style (was: C-DATABASE B-PLUS a quick look)
Mark Brader
msb at sq.uucp
Tue Dec 20 15:03:09 AEST 1988
Wayne A. Throop (throopw at xyzzy.UUCP) made, in <2404 at xyzzy.UUCP>, some
criticisms of a certain piece of code including these lines:
> > int p = 0;
> > while ( s[p] != NULL ) {
The last of these was:
> Fifth, the object of this exercise is somewhat more naturally cast in
> terms of pointers rather than subscripting in C.
Wayne went on to cite two admittedly minor justifications for this.
And I'd like to add another: avoiding the use of "int" for the subscript!
Remember that "int" is allowed to be as small as 16 bits. It is quite
conceivable that s[] has more than 32767 elements in it, so p can
overflow, followed by God-knows-what (or as the X3J11 people say, by
"undefined behavior"). A similar problem can exist if we make p "unsigned";
in this case it would be an infinite loop.
On the other hand, some compilers wouldn't allow the object's dimension
to exceed an int's range, so declaring p as "long" could be wasteful.
If we use pointers instead of subscripts to step through the array,
no such problem can exist. A pointer that points to the beginning of
an array is guaranteed to be incrementable to the end of the array
(plus one more time, in Draft ANSI C); and there is only one size of
pointer variable (in true C, anyway): the right size.
Mark Brader "Those who do not understand UNIX
SoftQuad Inc., Toronto are condemned to repeat it."
utzoo!sq!msb, msb at sq.com -- Henry Spencer
More information about the Comp.lang.c
mailing list