Path: utzoo!utgpu!news-server.csri.toronto.edu!torsqnt!geac!alias!bmcphers From: bmcphers@alias.UUCP (Brent McPherson) Newsgroups: comp.lang.c++ Subject: Re: C++ coding standards (Comment needed) Keywords: standard,variables Message-ID: <1990Aug13.182226.24141@alias.uucp> Date: 13 Aug 90 18:22:26 GMT References: <2161@runxtsa.runx.oz.au> Sender: news@alias.uucp (USENET News) Organization: Alias Research Inc., Toronto ON Canada Lines: 40 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". > >I think that this is an absolutely insane standard for the following reasons: >[reasons deleted] I have to disagree with you. There are important reasons for not doing this in C++. If all variables in C++ were declared at the start of a routine, then all the constructors/destructors would get executed on each invocation of the routine (even if the variables are not used because of control flow within the routine). The problem is also worse because of nested constructors and destructors with inherited classes. A better plan would be to declare all variables at the start of each block so objects that aren't used (depending on which blocks are executed) don't have their constructors/destructors called. This distributes the cost evenly over the entire routine and can result in less overhead in most cases (rather than a large, constant cost at entry/exit of the routine). I also like having variables declared close to where they are used since you will be less likely to forget to remove old variable declarations as the code evolves. This is not so much of a problem these days since most compilers will warn of unused/uninitialized variables. 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. BTW. I think constant cursoring to the top of a routine to add/delete/modify variables increases development time. Also, readability/understandability are a matter of personal preference (remember the brace/format/spacing debates between various C programmers). >Edward Birch -- Brent McPherson Alias Research Inc. bmcphers%alias@csri.toronto.edu