Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!cs.utexas.edu!sdd.hp.com!decwrl!ucbvax!mtxinu!rtech!ingres!llama!jas From: jas@llama.Ingres.COM (Jim Shankland) Newsgroups: comp.lang.c++ Subject: Declare at first use? (was Re: C++ coding standards) Keywords: standard,variables Message-ID: <1990Aug17.191939.3990@ingres.Ingres.COM> Date: 17 Aug 90 19:19:39 GMT References: <2161@runxtsa.runx.oz.au> <1990Aug13.182226.24141@alias.uucp> <56642@microsoft.UUCP> Reply-To: jas@llama.Ingres.COM (Jim Shankland) Organization: The Eddie Group Lines: 29 In article <56642@microsoft.UUCP> jimad@microsoft.UUCP (Jim ADCOCK) writes: >In article <1990Aug13.182226.24141@alias.uucp> bmcphers@alias.UUCP (Brent McPherson) writes: >>Finally, common sense should prevail. If a variable is first assigned a value >>within a loop it should be declared outside the loop just in case the compiler >>decides to create the variable on the stack for each loop iteration. >Hm, I'm not sure I understand what you're trying to say here. In the >following code: > > for (int i=0; i<1000; ++i) > { > FOO foo(i); > foo.DoSomething(); > } >It is certainly not the case that a thousand foos reside simultaneously >on the stack. Yes, but if you don't want foo's constructor and destructor to be called on each loop iteration, you probably want to declare foo outside the loop, even if it only gets used inside the body of the loop. (Even in C, it's technically incorrect to declare an auto variable inside a loop body, and expect its value to persist across loop iterations. In practice, you get away with it -- at least I've never seen a system where you don't -- because the compiler would have to go out of its way to trash the value between iterations.) jas