hardcoded constants
Barry Margolin
barmar at think.COM
Sat Dec 17 03:23:07 AEST 1988
In article <1988Dec15.190331.2986 at utzoo.uucp> henry at utzoo.uucp (Henry Spencer) writes:
>Trouble is, often it's almost impossible to devise a meaningful name.
>I'm not talking about hard-coding things like choice of control characters,
>but about things like (in a function to concatenate two strings with a
>'/' in between):
>
> foo = malloc(strlen(a)+strlen(b)+2); /* 2 for '/' '\0' */
>
>Now, what's a good name for that "2", and how does naming it improve
>readability?
I have a few ideas:
1) When I've done this in other languages, I've used something like
strlen("/") instead of the 2. Unfortunately, in C I'd still have to
say "+1", which I'd then want to comment with /* leave room for the
trailing null */, since I don't think there's an expression that will
return the total space taken up by a string. I like this because I
would expect a reasonable compiler to constant-fold the expression,
and it says exactly what the extra space is there for.
2) Define constants: #define PATH_DELIMITER "/"
#define ROOM_FOR_PATH_DELIMITER (strlen(PATH_DELIMITER))
#define ROOM_FOR_TRAILING_NULL 1
then use ROOM_FOR_PATH_DELIMITER+ROOM_FOR_TRAILING_NULL.
ROOM_FOR_TRAILING_NULL would probably be useful in other places if the
program does lots of concatenation like this. Those names are pretty
meaningful. If you're worried that strlen("/") won't be
constant-folded, put the 1 in the #define, with the expression in a
comment.
3) Word the comment differently: /* allocate room for the two strings,
a separator and trailing null */. This way, it doesn't sound as if
you're defining the 2, just explaining what the statement as a whole
is doing. The 2 is implicit, and doesn't really stand for anything.
Barry Margolin
Thinking Machines Corp.
barmar at think.com
{uunet,harvard}!think!barmar
More information about the Comp.lang.c
mailing list