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

Each style is "more cohesive" than the other, but measured along different axes.

Declaring variables at the top keeps variable declarations close to each other; declaring variables close to where they're used keeps, obviously, declarations close to use.




> Declaring variables at the top keeps variable declarations close to each other

And that one is not very useful to a human. Declaring variables near their usage is useful to a human. Understanding the code requires less (human) working memory.

The reason that old C code declared all variables at the top is because it made the earliest compilers easier to implement in a single pass: the compiler could tell up front how much stack space was necessary for the function call before encountering statements. The early compilers could scan all of the statements, tabulate the stack space required, and then emit the machine code to reserve that amount of stack space, before proceeding to parse and compile the following statements. Modern compilers are multi-pass and can scan the function and compute the stack space before beginning to generate machine code.

Writing code in that style is an example of humans optimizing for the machine, rather than vice versa. Modern compilers don't have this limitation. I haven't read an argument that code written in this style is actually preferable for humans, and in my opinion and experience, it is not.


Makes sense. I have to take a look at the project's coding style a bit closer.


Agreed!




Consider applying for YC's Spring batch! Applications are open till Feb 11.

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

Search: