Path: utzoo!attcan!uunet!husc6!bloom-beacon!adam.pika.mit.edu!scs From: scs@adam.pika.mit.edu (Steve Summit) Newsgroups: comp.lang.c Subject: Re: hardcoded constants Message-ID: <8510@bloom-beacon.MIT.EDU> Date: 18 Dec 88 04:32:08 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: daemon@bloom-beacon.MIT.EDU Reply-To: scs@adam.pika.mit.edu (Steve Summit) Lines: 26 In article <1988Dec15.190331.2986@utzoo.uucp> henry@utzoo.uucp (Henry Spencer) writes: >...things like (in a function to concatenate two strings with a >'/' in between): > > foo = malloc(strlen(a)+strlen(b)+2); /* 2 for '/' '\0' */ You're all going to think I'm crazy, but I always write this as ... malloc(strlen(a)+1+strlen(b)+1) ... to make it that much more obvious how the length is being calculated. (A comment still helps.) This is merely a strict application of Kernighan and Plaugher's adage, "Let the computer do the dirty work." Why make the person reading the code "decompile" the 2 into its constituents? (This example is admittedly trivial, but in more complicated cases it can make a big difference.) C compilers can (and do) employ associativity and commutativity to "fold" the two separate 1's into a single 2, at compile time, so code like this is in no way less efficient. (I'm not sure how much of the compiler's freedom to rearrange expressions is being abrogated under ANSI C.) Steve Summit scs@adam.pika.mit.edu