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

I was reading '21st Century C' (I strongly recommend it for anyone writing C on a regular basis), and the author also argued against declaring all the variables up front. I don't quite know why, but I had a very strong reaction against it. As far as best practices go, I would try to keep every function small enough that you can find all the stack variables easily. If the function gets too hairy, refactor it so you can follow where the variables are going.

I don't see any advantages of declaring variables up front. Not all variables should be at the function scope. Often I have a local variable that is only used inside one branch of a conditional, why should I declare that at the top? Declaring things up front also separates the type from the usage, which makes things harder to read and takes up twice as many lines in some cases.

Maybe I miscommunicated; I'm not against declaring variables at scopes smaller than the function - I declare variables at the top of conditional branches as well. I still don't buy the 'twice as many lines' reason for mixing assignment and declaration.

You should be using const variables as much as possible (and in general preferring immutable data). In that case assignment and declaration _must_ take place at the same location.


There's an upvote button to agree with a comment, no need to post a single word. Generally, terse answers aren't really appreciated here (unless they're very good).

you can find all the stack variables easily

You can't do that unless you look at the assembly output. While there may have once been a time in history where "locally-scoped variable == entry on stack", those days are long gone. Any decently smart compiler (i.e. GCC and LLVM) will use registers in preference to the stack, and will collapse local variables whose lifetimes do not overlap into a single storage location.

My bad, I meant locally scoped, I tend to think in terms of "it's on the stack (or a register), or it's on the heap (because it's been malloc'd and needs to be freed)". I do need to review my terminology...

The only time you actually need to declare variables up front nowadays is if you have a goto that would otherwise skip over stack-allocated variable declarations. It's only a problem on certain compilers, but there are enough of them that it's best to keep variable declarations up front in such cases.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact