DEV Community

Discussion on: Should You Truly Never Use var?

Collapse
 
paulsmithkc profile image
Paul Smith

The "variables first approach" is an anti-pattern that originated in Fortran and continued with C, because compilers the time were not very smart and did not do a good job of optimizing code.

Putting all your variables at the top forces the compiler to allocate space for all of them on the stack from the beginning, even if you don't end up using them. It also prevents the compiler from intelligently warning you about uninitialized variables. That second point may seem small, but can be a deadly problem in medical software.

If you switch to use const to declare most of your variables when you need them there are several benefits:

  • Faster Code, because the compiler tends to put variables into registers instead of the stack
  • Less stack swapping because the compiler knows what variables are "live" and which ones have fallen out of scope
  • Better Readability, because your reader isn't hit with a wall of variables which may or may not be used later, but have an initial state which must be tracked and an unknown purpose.
  • By declaring the variables when you can actually initialize them and use them, the reader has a clear understanding of the purpose of the variables and doesn't have to track 10 variables that you might use later.
  • You don't accidentally use a variable that either hasn't been initialized or has been initialized to a non-sensical value. (Initializing to zero isn't always safe. A lot of people have died from programs where variables where erroneously initialized to zero.)