Search code examples
cloopstemporary

Should I bring temporary variable declarations out of loops in C and C++?


Here is what I mean, suppose I have code like:

for (int i = 0; i < 1000; i++) {
    char* ptr = something;
    /*
    ... use ptr here
    */
}

It seems that char* ptr gets allocated every time in the loop, making it ineffective?

Is it more effective to write this?

char* ptr = something;
for (int i = 0; i < 1000; i++) {
    /*
    ... use ptr here
    */
}

Please comment on this interesting problem. Thank you!

Thanks, Boda Cydo.


Solution

  • It can make a performance difference, but many optimizing compilers undertake this optimization for you, if appropriate. This is called "loop-invariant code motion".