1

One of my programming philosophy is that defining variables just before it is really being used the first time. For example the way of defining variable 'x', I usually don't write code like this:

var total =0;
var x;
for(int i=0;i<100000;i++)
{
   x = i;
   total += x;
} 

Instead, I prefer to this:

var total = 0;
for(int i=0;i<100000;i++)
{
   var x = i;
   total = +x;
} 

This is just an example code, don't care about the real meaning of the code.

what downsides is the second way? performance?

diwatu
  • 5,641
  • 5
  • 38
  • 61
  • 1
    Just measure that. With an optimizing compiler, the difference will usually be NIL. Now, if `x` were non-POD there might be a difference because the compiler may not be able to decide that construction/destruction has no _observable_ side-effects. That said, avoid excess scope. It's a matter of (defensive) style, and allows for easier code (re)factoring. – sehe Jun 30 '13 at 01:41
  • Similar question here: http://stackoverflow.com/questions/407255/difference-between-declaring-variables-before-or-in-loop – Dan Teesdale Jun 30 '13 at 01:42
  • 1
    `var x` will have difference scopes. – Bill Jun 30 '13 at 01:43
  • These statements aren't really comparable; `x` will have a different scope in both examples. If you intend to use `x` in your program later, you won't have an efficiency problem, you'll have a *bug*. – Makoto Jun 30 '13 at 01:47
  • A compilation error is not a bug. Though, of course the language isn't specified. @Giswin Please clarify the language? (Some languages, e.g. `javascript` are known to have surprising semantics with regards to variable scope and initialization) – sehe Jun 30 '13 at 01:48
  • More importantly, the loops do totally different things! The second loop will end up with `total` equal to `99999` – sehe Jun 30 '13 at 01:50
  • Recommend you change `total = +x;` to `total += x;`. See @not-sehe – chux - Reinstate Monica Jun 30 '13 at 04:35

5 Answers5

4

Don't bother yourself with performance unless you really really need to (hint: 99% of the time you don't need to).

My usual philosophy (which has been confirmed by books like "The Art of Readable Code") is to declare variables in the smallest scope possible. The reason being that in terms of readability and code comprehension the less variables you have to think about at any one time the better. And defining variables in a smaller scope definitely helps with that.

Also, often times if a compiler is able to determine that (in the case of your example) moving the variable outside of the for loop to save having to create/destroy it every iteration won't change the outcome but will help performance he'll do it for you. And that's another reason not to bother with performance, the compiler is usually smarter about it than we are.

Borgleader
  • 15,826
  • 5
  • 46
  • 62
3

There is no performance implications, only the scope ones. You should always define variables in the innermost scope possible. This improves readability of your program.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Mmm. Is an assignation cheaper than reserving memory for a variable and then assigning it a value? – rendon Jun 30 '13 at 01:59
  • @RafaelRendonPablo who says that's what the compiler does? Maybe Borland C++ 3.1 with no optimizations will. – sehe Jun 30 '13 at 01:59
  • Yes. I know that compilers can optimize your code but that isn't always guaranteed. – rendon Jun 30 '13 at 02:01
  • @rafaelrendonpablo the compiler could choose towait 3 million years between statements, and it would be legal C++: lack of guarantee that tye compiler will be not stupid is uninteresting. There are easy optimizations that you must be aware of, and can assume happen barring evidence otherwise. If you are writing for some esoteric platform you should write differently if your compiler is crippled. – Yakk - Adam Nevraumont Jun 30 '13 at 02:11
  • 1
    Disagree that there are _no_ performance implications. `var x` could be a hugely expensive constructor/destructor whiles it assignment operator is minimal. With well known types like 'int', of course - no issue, but we do not know details about `var`. – chux - Reinstate Monica Jun 30 '13 at 04:40
  • @chux In the OP's example `var` stands for `int`, because it is assigned `i`, which is explicitly declared `int`. Of course deferral of a constructor to the point when it is needed can save you a lot of time in cases when the block with the constructor is skipped. – Sergey Kalinichenko Jun 30 '13 at 04:43
  • Thanks. IMHO, I saw the tagging of C++ and the OP use of var, rather than int, as a purposeful simplification that var may be something non-trivial. – chux - Reinstate Monica Jun 30 '13 at 05:09
  • @chux I remember pointing that out in an [early comment](http://stackoverflow.com/questions/17386326/what-downsides-is-declaring-variables-just-before-first-time-use-it#comment25239810_17386326) :) – sehe Jun 30 '13 at 10:27
0

The only "downside" is that the second version need compiler support. Old compilers needed to know all the variables the function(or a scope inside it) will be using, so you had to declare the variables in a special section(Pascal) or in the beginning of the block(C). This is not really a problem nowadays - C is the only language that does not support declaring variables anywhere and still being widely used.

The problem is that C is the most common first-language they teach in schools and universities. They teach you C, and force you to declare all variables at the beginning of the block. Then they teach you a more modern language, and because you are already used to declaring all variables at the beginning, they need to teach you to not do it.

If your first language allows you to declare a variable anywhere in the function's body, you would instinctively declare it just before you use it, and they wouldn't need to tell you that declaring variables beforehand is bad just like they don't need to tell you that smashing your computer with a 5 Kilo hammer is bad.

Idan Arye
  • 12,402
  • 5
  • 49
  • 68
0

I recommend, like most, to keep variables within an inner scope, but exceptions occur and I think that is what you are seeking.

C++ potentially has expensive constructor/destructor time that would be best paid for once, rather than N times. Compare

void TestPrimacyOfNUnsignedLongs(int n) {
  PrimeList List();  // Makes a list of all unsigned long primes
  for (int i = 0; i<n; i++) {
    unsinged long x = random_ul();
    if (List.IsAPrime(x)) DoThis();
  }
}

or

void TestPrimacyOfNUnsignedLongs(int n) {
  for (int i = 0; i<n; i++) {
    PrimeList List(); // Makes a list of all unsigned long primes
    unsinged long lx = random_ul();
    if (List.IsAPrime(x)) DoThis();
  }
}

Certainly, I could put List inside the for loop, but at a significant run time cost.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
-4

Having all variables of the same scope in the same location of the code is easier to see what variables you have and what data type there are. You don't have to look through the entire code to find it. You have different scopes for the x variable. In the second example, you won't be able to use the x variable outside the loop.

davidstar
  • 220
  • 3
  • 9
  • Well, make all your variables global and sort them by name. No, by type. Wait, what's the recommended order? – sehe Jun 30 '13 at 01:46
  • Why would you ever need to "see what variables you have"? This was useful a few decades ago when IDEs were primitive, but is not an issue now. – Dave Doknjas Jun 30 '13 at 03:23