Path: utzoo!utgpu!watserv1!watmath!att!dptg!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: C++ coding standards (Comment needed) Keywords: standard,variables Message-ID: <11185@alice.UUCP> Date: 14 Aug 90 17:28:56 GMT References: <2161@runxtsa.runx.oz.au> <1990Aug13.182226.24141@alias.uucp> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 56 In article <2161@runxtsa.runx.oz.au> edward@runxtsa.runx.oz.au (Edward Birch) writes: > A friend of mine works with a large organization where they have defined a > standard that "variables must be declared where first used". `Must' is too strong, but I do think there is often an advantage to declaring a variable at its first use. For example: void f() { int i; // a bunch of code if (i > 0) g(); // ... } Is the test `i > 0' valid or not? The answer is that it's valid if and only if something in `a bunch of code' initialized `i.' That is, during at least part of `a bunch of code,' variable `i' exists but is uninitialized. If `i' were initialized at its point of declaration, it would never be uninitialized. In other words, if you initialize all your variables when you declare them, they won't be uninitialized. Now one might argue that this is just a matter of taking care to get it right. After all, uninitialized variables aren't always dangerous -- you just have to make sure not to use them until you've initialized them. But many classes initialize things for you: String s; // ... s = "hello"; With every String class I've seen, `s' will be initialized to the null string at its declaration. Later that initial value must be discarded and replaced with "hello" . It is almost always faster to say // ... String s = "hello"; As to the argument that it's harder to find declarations if they're scattered through your functions: if your function is so big that it matters, you should probably split it up anyway. -- --Andrew Koenig ark@europa.att.com