25

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

3 Answers 3

17

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I meant is the memory reallocated at each iteration. I've changed the question.
14

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

1 Comment

Defining in the loop is clearer and might produce more optimised code since the compiler knows the lifetime (although probably not for a simple type)
1

For most modern compilers, this doesn't matter. They will assign processor registers or place the variables on the stack as efficiently as possible.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.