hardcoded constants

John H. Remmers remmers at m-net.UUCP
Sat Dec 24 03:28:26 AEST 1988


In article <1104 at goofy.megatest.UUCP> djones at megatest.UUCP (Dave Jones) writes:
>From article <2636 at m2-net.UUCP>, by remmers at m-net.UUCP (John H. Remmers):
>...
>> 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)
>> 
>
>You are a candidate for SLMA (Silly Little Macros Anonymous).

Well, maybe, maybe not.  Hiding the 1 for the null byte in a macro
definition is a defense against forgetting it.  Promiscuous ad hoc
invention of macro names is of course Bad Programming Practice;
what I was trying to say, perhaps not too clearly, is that *if* dynamic
allocation of space for strings is a frequently-needed operation in
an application, *then* a macro (or maybe a set of macros) might be
worthwhile, and that the example at hand is a natural place to use it.

>But if you don't like the naked "1", how about this?
>
>foo =  malloc( strlen(s) + strlen(t) + sizeof('\0'));

A couple of people have pointed out to me in mail that 
sizeof(<character-constant>) is wrong, since a character-constant is 
an int.  Hence sizeof('\0') = sizeof(int), usually 2 or 4, and more 
space is allocated than needed.  Actually, I don't mind the naked
"1"; it was the naked "2" I was questioning.


-- 
John H. Remmers               | ...umix!m-net!remmers
Dept. of Computer Science     |---------------------------------------------
Eastern Michigan University   | My opinions and those of my employer are the
Ypsilanti, MI 48197           | same, but my employer doesn't know that yet.



More information about the Comp.lang.c mailing list