Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ remake a variable defined in a loop?

Tags:

c++

loops

memory

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
}
like image 617
Galaxy Avatar asked Dec 03 '22 13:12

Galaxy


2 Answers

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.

like image 78
Brian Bi Avatar answered Jan 02 '23 05:01

Brian Bi


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.

like image 33
Remy Lebeau Avatar answered Jan 02 '23 04:01

Remy Lebeau