msc
msc

Reputation: 34578

for loop variable optimization in C/C++

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++) 
{

}

Upvotes: 0

Views: 355

Answers (2)

Luis Cabrero
Luis Cabrero

Reputation: 66

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.

Upvotes: 0

Lundin
Lundin

Reputation: 213493

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.

Upvotes: 6

Related Questions