Page 1 of 1
Does the program become slow if I define variable in a loop?
Posted: Tue Apr 18, 2006 2:50 pm
by ImLazy
For example, this code:
Code: Select all
for (int i = 0; i < 100; i++) {
int a = i;
f(a);
}
Will the variable "a" be allocated 100 times? Or it is allocated at the beginning of the loop and destroyed when the loop finishes?
Posted: Tue Apr 18, 2006 6:02 pm
by Darko
Interesting - I just tried both versions (declared inside and outside) and they compile in exactly the same way. (gcc 3.4.3)
Well, I just printed a inside the loop, I don't know what would happen if you do something more complicated.
Darko
Posted: Tue Apr 18, 2006 8:18 pm
by Krzysztof Duleba
This is because static variables are not really "allocated". Static variable is just an address on stack that is chosen during compilation.
Posted: Sat Apr 22, 2006 4:00 pm
by Moha
These is no diffrence in running time. But the C++ draft suggest us to declare variable inside the loop as much as possible. and that is why C++ compiler can optimize on memory. And You should know that in C/C++ local variable alocated in stack, but sometimes there is some cost of changeing between memory farmes. So declaring a variable inside a loop is much easier and safer.