hardcoded constants

John H. Remmers remmers at m-net.UUCP
Mon Dec 19 22:44:47 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?
>
The "2" can be viewed as the incidental result of a bookkeeping operation:
a "+1" for the null terminator in a string concatenation, and a "+1" for
the extra '/' character.  So naturally it's hard to name in an illumi-
nating way.  

I always tell my students that bookkeeping is best left to the computer; 
to improve readability, name the *concepts* and let the compiler sort out 
the bookkeeping details.  Hence the "2" probably shouldn't be in the 
source code at all, named or otherwise.

The space requirement for a string concatenation is a frequently-needed
value; it's worth having a macro to represent it:

	#define  Catspace(s,t)  (strlen(s) + strlen(t) + 1)

In terms of this, the malloc() call can be written:

	foo = malloc(Catspace(s,t) + sizeof('/'));

thus making it explicit that you're concatenating two strings and
allocating one more byte for an extra character.  Readability is
improved, and the question of naming the "2" never comes up.



More information about the Comp.lang.c mailing list