When a variable is declared inside a loop in C++, does C++ remake the variable in each iteration of the loop? I mean, does it reallocate memory for another num
variable? So if the loop iterates 5 times, do you get 5 separate num
variables with their own unique values? Is it a better practice to declare a variable before the loop starts, even if that variable will only be used inside the loop? What if for instance I want to use the variable as a counter or placeholder?
// is this better code?
// int num;
for (int i = 0; i < 5; i++) {
int num;
// do stuff with num
}
Yes, if num
is definition inside the loop, then it will represent a different variable every time the loop runs. Each time control passes through its definition, it will be newly initialized (if at all) and each time an iteration of the loop ends, it will be destroyed.
A variable should normally be declared in the narrowest scope possible. So if num
does not need to retain its value from one iteration to the next, it should normally be defined inside the loop. If it does need to retain its value from one iteration to the next, it must be defined outside the loop.
There are some exceptions to this stylistic best practice, such as when the initialization is expensive.
The compiler may optimize memory usage so the variable is only physically allocated one time and then reused on each loop iteration. But, in general, YES, scoping rules require each loop iteration to operate on a distinct instance of the variable. And in the case of complex types, like classes/structs, that means calling a constructor and destructor on the variable on each loop iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With