Path: utzoo!attcan!uunet!seismo!sundc!pitstop!sun!oliveb!ames!think!barmar From: barmar@think.COM (Barry Margolin) Newsgroups: comp.lang.c Subject: Re: hardcoded constants Message-ID: <33604@think.UUCP> Date: 16 Dec 88 17:23:07 GMT References: <1988Dec8.173158.11839@utzoo.uucp> <846@starfish.Convergent.COM> <9134@smoke.BRL.MIL> <1988Dec13.172306.16195@utzoo.uucp> <5146@bsu-cs.UUCP> <1988Dec15.190331.2986@utzoo.uucp> Sender: news@think.UUCP Reply-To: barmar@kulla.think.com.UUCP (Barry Margolin) Organization: Thinking Machines Corporation, Cambridge MA, USA Lines: 43 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? 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@think.com {uunet,harvard}!think!barmar