C Programming – Disadvantages of Inner Block Declarations

ccoding-styledeclarations

At the place where I work, there are explicit guidelines for placement of declarations of variables. According to that, it is required to put them at the global level and / or at the beginning of functions, and not in inner blocks (such as a for loop). Since they've been specified by persons more experienced than I am, I'm sure that there must be a good reason for it, but I cannot figure out what that might be. It would be nice to know if there are any compile time / run time advantages at having them declared at a bigger scope.

Best Answer

I see two main advantages:

  • Reusing variable names with a different type is prevented.
  • It becomes clear at an earlier time that a routine needs to be refactored. The variables at the top become a major mess fairly quickly, and this mess is easy to recognize.

Any compiler worth its salt will optimize away the scope of the variables anyway, so it's purely a formatting concern.

For my two cents, I'd still prefer the innermost declaration of the variable to transport the intent of scope to the compiler. If you intended to have a variable only accessed within a loop, you can catch any later reference at compile time when you declare the variable in the loop.

Related Topic