hardcoded constants
Steve Summit
scs at adam.pika.mit.edu
Sun Dec 18 14:32:08 AEST 1988
In article <1988Dec15.190331.2986 at utzoo.uucp> henry at utzoo.uucp (Henry Spencer) writes:
>...things like (in a function to concatenate two strings with a
>'/' in between):
>
> foo = malloc(strlen(a)+strlen(b)+2); /* 2 for '/' '\0' */
You're all going to think I'm crazy, but I always write this as
... malloc(strlen(a)+1+strlen(b)+1) ...
to make it that much more obvious how the length is being
calculated. (A comment still helps.) This is merely a strict
application of Kernighan and Plaugher's adage, "Let the computer
do the dirty work." Why make the person reading the code
"decompile" the 2 into its constituents? (This example is
admittedly trivial, but in more complicated cases it can make a
big difference.)
C compilers can (and do) employ associativity and commutativity
to "fold" the two separate 1's into a single 2, at compile time,
so code like this is in no way less efficient. (I'm not sure how
much of the compiler's freedom to rearrange expressions is being
abrogated under ANSI C.)
Steve Summit
scs at adam.pika.mit.edu
More information about the Comp.lang.c
mailing list