Depending on what you are referring to, there are ways to avoid so may loose variables.
1) Throw away variables should not be global or stored in a class or struct. Instantiate them inside of functions like the int result in MrGodin's example, though I prefer to initialize on the same line as declare. const int return = d == 1 ? 1 : -1;
For one, this allows me to make my temporary variables const ( performance optimization, safety check ), and two I don't have to remember to initialize them before using them ( compiler error if used before initializing ).
2) Use for loops instead of while loops when possible. For loops allow you to initialize a variable inside the loops declaration and won't live past the loop, unlike the while loop where you must declare before the while and they live after the while.
3) Use the fact that functions that return values can be used directly instead of storing to a named temporary. const int result = 5 + Add(7,3); // result = 15;
The result of Add(7,3) is stored in memory, then added to 5 and that result is stored in const int result.
If you only need it inside a function, create it inside the function.
If you only need it inside a loop, create it inside a loop.
You can even use curly braces {} to limit the scope of the ints, so you can reinstantiate them with the same name.
Code: Select all
// i only lives until end of loop
for( int i = 0; i < numPersons; ++i )
{
{
// Person and name live only in this block
const Person& person = boy_name_list[i];
const char* name = person.GetName();
std::cout << "The boy at index " << i << "is named: " << name << std::endl;
std::cout << "They are: " << person.GetAge() << " years old." << std::endl;
}
// Person and name are destroyed
{
// Person and name live only in this block
const Person& person = girl_name_list[i];
const char* name = person.GetName();
std::cout << "The girl at index " << i << "is named: " << name << std::endl;
std::cout << "They are: " << person.GetAge() << " years old." << std::endl;
}
// Person and name are destroyed
}
// i is destroyed
I prefer to be a little verbose in my coding. It allows me to step through the code mentally and literally while debugging and see what the values are as I go. Plus, if you have functions returning values to functions as parameters, then you have to step through each of those functions before you get to the top level function and by that time, you've forgotten what the values were that were being passed in.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com