T
Thomas Matthews
Hi,
While coding programs, I cam about a conundrum regarding
variables defined in an iterative loop.
The issue is whether it is more efficient to factor the
definition out of the loop or maintain encapsulation by
leaving it inside the loop?
Common stuff for examples:
class Data;
bool Is_Data_Valid(const Data &);
ifstream data_file;
Example 1: Definition inside loop:
Data my_datum;
while (data_file >> my_datum)
{
bool status; // *** Definition within loop. ***
status = Is_Data_Valid(my_datum);
if (!status)
return;
}
Example 2: Definition outside loop:
Data my_datum;
bool status; // *** Definition outside of loop ***
while (data_file >> my_datum)
{
status = Is_Data_Valid(my_datum);
if (!status)
return;
}
Reasonings:
1. In the first example, the variable is defined where
it is used. The variable is only used within the
scope of the loop.
2. The variable in the first example is created for
each iteration of the loop.
3. In the second example, the variable is available
outside of the loop (perhaps poor encapsulation).
4. However, the variable is only created once.
Any recommendations, or is this a religious issue?
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
While coding programs, I cam about a conundrum regarding
variables defined in an iterative loop.
The issue is whether it is more efficient to factor the
definition out of the loop or maintain encapsulation by
leaving it inside the loop?
Common stuff for examples:
class Data;
bool Is_Data_Valid(const Data &);
ifstream data_file;
Example 1: Definition inside loop:
Data my_datum;
while (data_file >> my_datum)
{
bool status; // *** Definition within loop. ***
status = Is_Data_Valid(my_datum);
if (!status)
return;
}
Example 2: Definition outside loop:
Data my_datum;
bool status; // *** Definition outside of loop ***
while (data_file >> my_datum)
{
status = Is_Data_Valid(my_datum);
if (!status)
return;
}
Reasonings:
1. In the first example, the variable is defined where
it is used. The variable is only used within the
scope of the loop.
2. The variable in the first example is created for
each iteration of the loop.
3. In the second example, the variable is available
outside of the loop (perhaps poor encapsulation).
4. However, the variable is only created once.
Any recommendations, or is this a religious issue?
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book