Loops and Variable Initialization

Jul 8, 2014 at 11:51pm
Will a variable initialized within a loop be destroyed and recreated every time it loops? Does it matter if the variable is initialized to something, or is a const?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main ( )
{
    while ( something is true )
    {
        const int a = 1;

        int b = 2;

        int c;


        // do something
    }
}
Jul 8, 2014 at 11:54pm
From your perspective, it is being created and destroyed each time. What really happens though depends on compiler optimizations.
Jul 8, 2014 at 11:58pm
That's what I thought it might be. Would you happen to know how VS 2012 handles it?
Jul 9, 2014 at 1:30am
That depends entirely on what "// do something" actually does.
Jul 9, 2014 at 1:49am
I guess the best thing to do then would be to initialize the variable outside of the loop and not worry about what different implementations might do.
Topic archived. No new replies allowed.