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.
If the variable is declared outside the loop, then it has the global scope as it can be used through-out the function and inside of the loop too. If the variable is declared inside the loop, then the scope is only valid inside the loop and if used outside the loop will give an error.
In short, you are right to do it. Note however that the variable is not supposed to retain its value between each loop. In such case, you may need to initialize it every time.
A for loop is like a function in that they are both used to execute the SAME code multiple times on DIFFERENT things. You need variables to stand in for the different things.
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.
It can make a performance difference, but many optimizing compilers undertake this optimization for you, if appropriate. This is called "loop-invariant code motion".
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