Path: utzoo!attcan!uunet!seismo!sundc!pitstop!sun!quintus!ok From: ok@quintus.uucp (Richard A. O'Keefe) Newsgroups: comp.lang.c Subject: Re: hardcoded constants Message-ID: <890@quintus.UUCP> Date: 19 Dec 88 06:23:28 GMT References: <15852@iuvax.cs.indiana.edu> <883@quintus.UUCP> <8512@bloom-beacon.MIT.EDU> Sender: news@quintus.UUCP Reply-To: ok@quintus.UUCP (Richard A. O'Keefe) Organization: Quintus Computer Systems, Inc. Lines: 32 In article <8512@bloom-beacon.MIT.EDU> scs@adam.pika.mit.edu (Steve Summit) writes: >In article <883@quintus.UUCP> ok@quintus.UUCP (Richard A. O'Keefe) writes: >>henry@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.