Path: utzoo!utgpu!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!rutgers!mailrus!b-tech!m-net!remmers From: remmers@m-net.UUCP (John H. Remmers) Newsgroups: comp.lang.c Subject: Re: hardcoded constants Message-ID: <2636@m2-net.UUCP> Date: 19 Dec 88 12:44:47 GMT References: <1988Dec8.173158.11839@utzoo.uucp> <846@starfish.Convergent.COM> <9134@smoke.BRL.MIL> <1988Dec13.172306.16195@utzoo.uucp> <5146 Reply-To: remmers@m-net.UUCP (John H. Remmers) Organization: M-NET, Ann Arbor, MI Lines: 35 In article <1988Dec15.190331.2986@utzoo.uucp> henry@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.