0

Which is faster in following two code snippets? and Why?

Declared loop index variable outside the for statement:

size_t i = 0;
for (i = 0; i < 10; i++) 
{

}

and

Declared loop index variable within the for statement:

for (size_t i = 0; i < 10; i++) 
{

}
5
  • In the first example you're initialising variable 'i' twice, you don't need to do that. Commented Apr 6, 2017 at 11:35
  • 2
    You can compare the resulting assembler code on for example godbolt.org and check yourself if they are equal and look up differences when they occur. Commented Apr 6, 2017 at 11:38
  • "Which is faster..." you need to measure. Commented Apr 6, 2017 at 12:10
  • if you call function from single thread, then declaring loop counter as local static variable for function will save you 2 operations with stack (push, pop) per function call. Only you can measure if it will have any impact (number of function calls) Commented Apr 6, 2017 at 12:23
  • Look at the assembly code and/or benchmark. It's the only way to be sure. (Though in this case I see no reason there could be any difference.) Commented Apr 6, 2017 at 13:31

2 Answers 2

6

Neither, they are equivalent and will yield the same machine code.

(The compiler will remove the redundant initialization of i twice from the first example.)

Where a variable is declared has very little to do with performance and memory use.

for (size_t i = 0; i < 10; i++) is usually considered the most readable.

for (i = 0; i < 10; i++) has the advantage that you can use the i variable after the loop is done - which makes most sense when the number of iterations is variable.

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

3 Comments

Being able to "use the i variable after the loop is done" is not necessarily an advantage.
@Peter it is not an advantage, but it can be one.
@Peter I was thinking of cases such as for(size_t i=0; i<length; i++) { str[i] = whatever; if(bad) break; } str[i] = '\0';
0

The only difference is that on the fist one, i is a global variable, and the second one is a local variable only for the loop.

3 Comments

There is no such thing as global-use variables. There are global variables, but here i is not global either in the first case. Enhance your question, you are on the right track.
@MichaelWalz If you want to be picky, there is no such thing as "global variables" either. The C language has scope and linkage, the formal term would be "file scope variable with external linkage".
Well, try to do this: for(int i=0; i<4;i++){ //do some stuff } printf("%d",i); Thats a local variable for the loop. If you declare it outside, you will be able to use it on another part of the code..

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.