Question on Variable Creation

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.

Thanks!

(:
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.
Last edited on
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?
That's one of the reasons.

A function should do _one_ thing, and do it well.

Very rarely can a large function not be broken down into smaller, reusable components.
Just to be specific about CS terminology, you want high cohesion.
What would be the reason to break my code into smaller segments or functions?


In addition to what others have said: code clarity. Breaking a large problem into smaller tasks greatly helps with that.

When functions are small and simple, it makes it easier to understand what the program is doing.

Consider this contrived example:

1
2
3
4
5
6
7
8
9
10
11
12
void StartCar()
{
  PutOnSeatBelt();

  AdjustMirrors();

  InsertKey();

  PressClutch();

  TurnKey();
}


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.
Last edited on
Topic archived. No new replies allowed.