You don't have to declare all your variables at the top of the function

But it's a lot nicer when you do

@dragon Not to, like make this a paragraph, but I think I prefer the opposite.

The main benefit of defining your variables later is that they're closer to the context in which they're used/relevant.

It's a bit of a balance between "is my code interesting/hard to understand because of the logic it's driving, or is my code interesting because of the computer things it's accomplishing?"

If it's the latter, I could see having the memory all allocated at the same time as being real helpful, but if it's the former, it can help with local readability. I prefer to work on things that are logically interesting, but computationally boring, so my preferences might make some sense here.

To each is their own, tho. :)

@starless so I agree except theres points where you need a variable for a loop and you just declare it in the loop for instance and that just feels gross to me

similarly like putting all my vars at the top encourages me to reuse stuff and be mindful of memory as opposed to just putting things in random places, plus it gives a little overview of what the program needs which is always a bonus for reading imo

like it deffo depends on what you're doing and especially if you're working in an environment where memory doesn't really matter it's fine and clearer but for what I do it's just a lot easier for me to just see everything a program needs at once

Follow

@dragon I think decreasing variable re-use is why most style guides I've used prefer local definitions over defs at the top of the function.

I think most compilers optimize lines like
for(int x = 0; x<3; x++)
{
int i = x +i
print(i)
}
such that i isn't actually re-allocated each time, but like, yeah, most places I've seen would have you define int i right before the loop, but not at the top of the function, and ideally, if i isn't used elsewhere, to wrap the whole thing in something for scope management. That loop does look a bit wasteful.

The little overview of what's to come is neat, though, I totally agree there.

· · Web · 1 · 0 · 1

@starless oh yeah absolutely, like I'm sure it's nice in a lot of cases!!

Sign in to participate in the conversation
Pixietown

Small server part of the pixie.town infrastructure. Registration is closed.