Reputation: 637
I often see two ways of writing for loops.
The first:
for (int i = 0; i < 10; i++) {
......
}
The second:
int i;
for (i = 0; i < 10; i++){
......
}
Is there a difference between the two methods in terms of execution efficiency?
Upvotes: 2
Views: 99
Reputation: 81
No there is no difference between the output produced by both the for loops .the only difference is about the scope of the variable i,declaring variable before the for loop makes it accessible even after the loop.
Upvotes: 0
Reputation: 36496
As other have already noted, the difference is scope, and in many cases there is no difference in efficiency of the program.
For the sake of being able to debug your code and reason about what it's doing, it's generally advisable to have variables exist for the smallest scope possible. The longer a variable exists, the more unintended things you can do to it. If i
is unneeded after the loop, scope it locally to the loop.
Consider just printing an array of ints:
void print_array(int *arr, size_t n) {
for (size_t i = 0; i < n; ++i) {
printf("%d\n", arr[i]);
}
}
But let's say we want to find the index of a value in an int array (with i
being n
indicating the value wasn't found):
size_t find_index(int val, int *arr, size_t n) {
size_t i;
for (i = 0; i < n && arr[i] != val; ++i) {
// Nothing required here.
}
return i;
}
In the latter case, the value of i
was needed after the loop completed, so it could not be scoped locally to the loop.
Upvotes: 3
Reputation: 51825
The difference is that, in the second code snippet, the variable i
is available (for inspection and use) after the for
loop has finished execution; in the first snippet, it is not.
If you don't use/inspect that i
variable after the loop (i.e. after the closing }
), then an optimizing compiler will likely produce the same code for both.
Upvotes: 1
Reputation: 33864
In terms of execution effeciency, no. These will compile to the same thing. See the compiler output here. In terms of functionality, yes, in a very minor way. The scope of i
is different. So, in the second example you could do this:
int i;
for (i = 0; i < 10; i++){
if (some_condition) {
break;
}
...
}
// use i for some other purpose, like indexing a vector or something.
But because of the scope of i
, you cannot do this in the first loop.
Upvotes: 1