Re-declaring object in a for loop - C++

点点圈 提交于 2019-12-02 06:44:39

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!