hardcoded constants
Richard A. O'Keefe
ok at quintus.uucp
Mon Dec 19 16:23:28 AEST 1988
In article <8512 at bloom-beacon.MIT.EDU> scs at adam.pika.mit.edu (Steve Summit) writes:
>In article <883 at quintus.UUCP> ok at quintus.UUCP (Richard A. O'Keefe) writes:
>>henry at utzoo.uucp (Henry Spencer) writes:
>>>- 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 recently had a very similar problem. A *superb* "name" for that 2 is
>> sizeof "/"
>
>Was this suggestion supposed to include a :-) ? sizeof("/") is a
>very poor substitute, in this case: it gets the right answer for
>the wrong reason. (The '\0' the compiler counts in the string
>constant "/" has little to do with the one which will be added
>to the final, concatenated string.)
Nope, it is the right answer for the right reason. The characters in
the byte array are exactly the characters which will be added. If you
were going to do sprintf(dest, "%s%s%s%s%s", a, "/", b, "/", c),
the size of dest would be strlen(a)+strlen(b)+strlen(c) + sizeof "//".
What I really prefer to do in a case like this is
#define arglen(x) (strlen(x)-2) /* strlen(x) - strlen("%s") */
static char fmt[] = "%s/%s/%s";
...
foo = malloc(sizeof fmt + arglen(a) + arglen(b) + arglen(c));
...
sprintf(foo, fmt, a, b, c);
Now if someone changes that to
static char fmt[] = "[%s.%s]%s;";
it still works.
More information about the Comp.lang.c
mailing list