Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables declared inside a loop

Tags:

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

versus

int n; for(int i=0;i<10;i++) {     n = getNumber();     printf("%d\n",n); } 
like image 964
Stuart Jones Avatar asked Jan 04 '12 23:01

Stuart Jones


People also ask

Can we declare variables inside for loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

What happens if you declare a variable inside a loop?

If a variable is declared inside a loop, JavaScript will allocate fresh memory for it in each iteration, even if older allocations will still consume memory.

Can we declare variables in for loop in C?

Yes, I can declare multiple variables in a for-loop.

What are the loop variables?

The loop variable defines the loop index value for each iteration. You set it in the first line of a parfor statement. For values across all iterations, the loop variable must evaluate to ascending consecutive integers.


2 Answers

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.

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

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.

like image 138
mmx Avatar answered Oct 21 '22 17:10

mmx


Any modern compiler would optimise these to the same machine code, so you should see no difference.

like image 36
Oliver Charlesworth Avatar answered Oct 21 '22 18:10

Oliver Charlesworth