Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

loops

temporary

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.

like image 810
bodacydo Avatar asked Jul 28 '10 13:07

bodacydo


People also ask

Should I declare variable inside loop or outside?

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.

Can we declare variables inside for loop in C?

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.

Do you need a variable for a for loop?

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.

Can we declare variable in 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.


1 Answers

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

like image 126
John with waffle Avatar answered Sep 18 '22 00:09

John with waffle