5 ms·
What is wrong with declaring local variables at the top of functions ?
by marios 10y ago
What is wrong with declaring local variables at the top of functions ?
- titzer 10y agoBecause you generally want to put declarations close to their uses to minimize their scope? Reduce cognitive load and improve local reasoning?
- wtbob 10y agoBut in general functions shouldn't really be all that long anyway (if they are, break 'em up!). I kinda like declaring my variables all at the top — I think it looks nice & clean.
- bluetomcat 10y agoEven in short functions, "declare it when it's needed" makes your program follow a data-flow style and enables you to use const more, since in many cases the initialization is the only assignment that you do to that variable.
- dllthomas 10y agoWhile the parent technically said "at the start of functions", at least C89 (I don't remember about K&R) allowed declarations at the start of any block. This is not incompatible with minimizing scope - just introduce more blocks. And in fact, introducing a block to bound the scope of a variable allows a smaller scope than simply declaring it halfway through a function, as you can also end it early.
- majewsky 10y agoIf you declare a variable as `const`, you have to initialize it during declaration. So you have to place the declaration exactly where the value expression becomes available.
- bluetomcat 10y agoAlso, it acts as a declaration of intent and makes the data dependencies in a function more explicit. If I declare a variable in the middle of a function, I am declaring intent that this variable shouldn't be used in the first half of the function – maybe the data it is supposed to hold cannot be available at that point.