Hacker News new | past | comments | ask | show | jobs | submit login

Because you generally want to put declarations close to their uses to minimize their scope? Reduce cognitive load and improve local reasoning?



But 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.


Even 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.


While 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.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: