Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!hplabs!hp-pcd!hplsla!jima From: jima@hplsla.HP.COM (Jim Adcock) Newsgroups: comp.lang.c++ Subject: Re: variable declaration Message-ID: <6590251@hplsla.HP.COM> Date: 13 Sep 89 17:46:16 GMT References: <953@ncratl.Atlanta.NCR.COM> Organization: HP Lake Stevens, WA Lines: 70 > Has anybody developed any style rules for this? I'm especially worried > about the tradeoff of readability for optimization. (This becomes a real > issue in loop indices) There shouldn't be any issue of optimization no matter where one declares one's variables using any modern optimizing compiler. The optimizing compiler will analyze what scope of the code your variable is actually used in, and will free that variable's register for other usage elsewhere. So feel free to do whatever style of declaration makes your code most readable. --- If a variable is widely used throughout a procedure, declare and initialize it at the start of a procedure. If a variable is only used locally in a procedure, perhaps only in a couple lines of code, then declare and initialize it where first used. But *don't* make the mistake of introducing a variable in the middle of your code, then using it again later. Of course, one isn't tempted to do this is one keeps one's routines small. Other no-nos: don't use the same variable name more than once in a routine with differing meanings, or with differing types. As the following example demonstrates, for-loop scope [for historical reasons] is not what one would wish when declaring dummy loop variables. You could handle this by adding curly braces to make a local scope, but this is not a common style. Maybe one should continue in the C style of declaring standard dummy loop variables at the start of a routine? #include void doSmethingWith(int i) {printf("%d\n",i);} void aLoopyRoutine() { for (int i=0; i<10; ++i) doSomethingWith(i); // more code for (int i=0; i<10; ++i) doSomethingWith(i*i); //error: two declarations of i } void aLoopyRoutine2() { {for (int i=0; i<10; ++i) doSomethingWith(i);} // curly braces make i local // more code {for (int i=0; i<10; ++i) doSomethingWith(i*i);} //okay; but not common style } void aLoopyRoutine3() { int i; //maybe just declare common dummy loop variables at start? for (i=0; i<10; ++i) doSomethingWith(i); // more code for (i=0; i<10; ++i) doSomethingWith(i*i); } void main() { aLoopyRoutine(); aLoopyRoutine2(); aLoopyRoutine3(); }