Search code examples
c++goto

If program exits loop by goto are local variables deleted?


Normally, when you exit, let's say for loop, variables declared inside are deleted. For example:

for(int i=0; i<10; i++)
{
    vector <int> v;
    for(int j=0; j<1000000; j++) v.push_back(j);
}

Despite creating vector with size of 1000000, memory is free after loop.

If we do sth like this:

for(int i=0; i<10; i++)
{
    vector <int> v;
    for(int j=0; j<1000000; j++) v.push_back(j);
    goto after_for;
}
after_for: ;

will the vector stay in memory or be deleted?


Solution

  • Will be deleted. The variable goes out of scope and hence destructor is called (and memory freed) This is guaranteed even if you exit this way:

    for(int i=0; i<10; i++)
    {
        vector <int> v;
        for(int j=0; j<1000000; j++) v.push_back(j);
        throw std::runtime_error("xyz") ;
    }