Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

c - Variables declared inside a loop

If I were to declare a variable inside of a loop, is it faster to have the declaration outside of the loop? Does the program reallocate the memory for n at each iteration or use the same memory location throughout?

for(int i=0;i<10;i++)
{
    int n = getNumber();
    printf("%d
",n);
}

versus

int n;
for(int i=0;i<10;i++)
{
    n = getNumber();
    printf("%d
",n);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Variables are not really "created" or "destroyed". They are concepts at the abstraction level of the programming language. The compiler is not required to have a one to one mapping between a variable and memory addresses. In practice, most of the time, stack space for local variables is allocated at once at the beginning of the function, so it won't make a difference in performance.

Note that, C++, unlike C, which doesn't have a notion for constructors, supports object construction and destruction, so if you were to define a variable of a class type in a for loop, like the following,

class MyClass { 
    public: MyClass() { cout << "hello world" << endl; }
};
//...
for (int i = 0; i < 10; ++i) {
   MyClass m;
} 

you'd call its constructor every time, effectively printing "hello world" ten times. This is very different from C declarations and should not be confused with it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...