在循环内声明的变量 [英] Variables declared inside a loop

查看:87
本文介绍了在循环内声明的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我要在循环内声明变量,将声明置于循环外是否更快?程序是在每次迭代时为n重新分配内存还是在整个过程中使用相同的内存位置?

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",n);
}

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

推荐答案

变量并不是真正的创建"或销毁"对象.它们是编程语言抽象层的概念.不需要编译器在变量和内存地址之间具有一对一的映射.实际上,在大多数情况下,局部变量的堆栈空间是在函数开始时立即分配的,因此不会影响性能.

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.

请注意,C ++不像C,它没有构造函数的概念,它支持对象的构造和销毁,因此,如果要在for循环中定义类类型的变量,如下所示,

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;
} 

您每次都会调用其构造函数,有效地打印"hello world"十次.这与C声明有很大不同,不应与C声明混淆.

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.

这篇关于在循环内声明的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆