这个局部变量声明是否会重复多次?

an *_*use 0 c++ variables

我听说我们应该尽可能地让变量变为本地变量,我同意.考虑以下代码:

int main()  {
    for(int i = 0; i<5; ++i)    {
        int temp;
        std::cin >> temp;
        std::cout << temp << std::endl;
    }
    return 0
}
Run Code Online (Sandbox Code Playgroud)

tempfor循环的局部变量.但是,我担心temp会在每个循环中声明,因此使程序运行得更慢.避免这种情况并tempfor循环外声明是否会更好?

int main()  {
    int temp;
    for(int i = 0; i<5; ++i)    {
        std::cin >> temp;
        std::cout << temp << std::endl;
    }
    return 0
}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 6

这对速度没有任何影响,只是temp在后一种情况下你把堆放的时间更长.

我更喜欢第一个,因为尽可能减少变量的范围是一个好习惯.