Does the program become slow if I define variable in a loop?

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Does the program become slow if I define variable in a loop?

Post 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?
I stay home. Don't call me out.
Darko
Guru
Posts: 580
Joined: Fri Nov 11, 2005 9:34 am
Location: Calgary, Canada

Post 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
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post 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.
Moha
Experienced poster
Posts: 216
Joined: Tue Aug 31, 2004 1:02 am
Location: Tehran
Contact:

Post 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.
Post Reply

Return to “C++”