I just had a simple question on proper procedure when it comes to creating variables in functions. I'm all about using good practices in my coding.
From my main() I call a function that does a large amount of stuff. I'm instantiating a lot of variables throughout the function. I was curious if it is a better practice to initialize them all at the top of the function .. (probably keeps things a bit more tidy, huh?), as opposed to keeping them in their respective "regions" of the function. Or is this really a personal preference thing? As I'm not too familiar with gcc, I just wanted to be sure that it wouldn't take more memory, or be less efficient with variable creation spread throughout my function.
Best practice is to limit variable scope as much as possible or, in other words, to declare them at the point of usage*multiple sources.
* See Effective C++ (3rd ed.) by Scott Meyers. Item 26: Postpone variable definitions as long as possible. * See C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Herb Sutter and Andrei Alexandrescu. Item 18: Declare variables as locally as possible.
To add onto that, if you function has several "sections" and each section needs a bunch of new variables, you might want to consider breaking that function down into smaller functions.
Disch: I always thought of functions as a way to prevent copying of code. I don't have any repetitive code that isn't already a function. What would be the reason to break my code into smaller segments or functions?
You aren't likely to insert/turn the key or put on the seat belt at any other time, so making them functions doesn't really help much with reusability... however making them functions here makes the overall flow simpler to understand.
Now imagine that the code for putting on your seat belt / inserting the key / turning the key was 10 or 20 lines each. No longer would this be so simple and straight-forward. You couldn't just glance at the function and see what it's doing -- all of the sudden you'd be looking at a full page of code.