What is the difference (memory wise) bewteen:
for(int x=0;x<100;x++)
{
int y = 1+x;
}
and
int y = 0;
for(int x=0;x<100;x++)
{
y = 1+x;
}
I've always wondered if they are the same or the first is a waste of memory?...
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Memory-wise, there is no difference. y is on the stack, wherever it’s declared within the method. Here the only difference is the scope of y: in the second case, it is restricted to the body of the for loop; in the first, it isn’t. This is purely at the language-level: again, y is allocated in exactly the same way, that is, on the stack.
Just to make this point perfectly clear, here’s a code example:
Here is the assembler generated in debug mode in both cases :
Even without knowing anything about assembly, you can see that both methods have exactly the same instructions. In other words, at the point where a is declared, nothing happens.
There is an important difference however if you are using any type that has a constructor, say, an std::vector: at the point where it is declared, the constructor is called, so if you declare it within a loop, it will be reconstructed each time through the loop. For example:
The situation gets worse if you are using new: these two pieces of code behave very differently: