I do have a question on variable re-declaration in loops.
Why declaring an object in a foor loop doesn't trigger the redeclaration error?
Do the object get destroyed and recreated at each iteration of the loop?
I'm inserting a sample code
class DataBlock {
int id;
string data;
public:
DataBlock(int tid=0,const string &tdata=""){
id=tid;
data=tdata;
}
}
int main(int argc, char *argv[]){
ifstream file;
int temp_id; //temporary hold the the id read from the file
string temp_data; //temporary hold the data read from the file
set <DataBlock> s;
//check for command line input here
file.open(argv[1]);
//check for file open here
file >> temp_id >> temp_data;
while (!file.eof()){
DataBlock x(temp_id,temp_data); //Legit, But how's the workflow?
s.insert(x);
file >> temp_id >> temp_data;
}
file.close();
return 0;
}
Why declaring an object in a foor loop doesn't trigger the redeclaration error?
A redeclaration error happens when you declare the same name twice (or more) in the same scope. That looks like
int i = 5;
int i = 6; // uh oh, you already declared i
In your loop you don't have that, you just have
loop
{
int i = 5;
}
So no redeclaration.
You could also have
int i = 5
{
int i = 6;
std::cout << i;
}
And not have a redeclaration error as the variables are in different scopes and you can have the same variable in multiple scopes. I this case 6
would be print as that i
is the i
that is in scope.
Do the object get destroyed and recreated at each iteration of the loop?
Yes. Think of a loop as a function that gets called multiple times. When you enter the body of a loop/function the variables declared in it get constructed1 and when you reach the end of the loop/function the variables are destroyed.
1: it is a little more complicated then that but we don't need to get into all those details in this answer
Why declaring an object in a foor loop doesn't trigger the redeclaration error?
No it does not.
Each time the for loop iterates, a new scope is entered and the objects created in the previous one are destructed and their storage allocation are freed.
for (int i=0 ; i<2 ; ++i) {
MyClass c;
}
will be as if:
{
int i=0;
{
MyClass c; // c(0)
} // c destructed, storage allocation freed
++i;
{
MyClass c; // c(1)
} // c destructed, storage allocation freed
++i;
}
c(0)
and c(1)
do share the same name, but in scopes without overlapping. Everything is fine.