buzhidao buzhidao - 2 months ago 8
C++ Question

Will this declaration of local variables atually repeat many times?

I heard that we should make variables as local as possible, I agree. Consider this code:

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


temp
is the local variable of the
for
loop. However, I am afraid that
temp
is declared at every loop, therefore make the program run slower. Would it be better to avoid this case and declare the
temp
outside the
for
loop?

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

Answer

That doesn't make any difference on speed, except that you put temp on the stack for longer time in the latter case.

I'd prefer the first one, as it is a good practice to minimize the scope of variables wherever possible.