Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize the iterator variable in for loop in C

Tags:

c

I'm sorry if it may be a stupid question. Last time, my friend told me that i should declare the iterator variable in the outside of the for loop when i develop on the embedded system, for example:

int i = 0;
for (i = 0; i < 10; i++) {
   // Do something
}

should not use as below:

for (int i = 0; i < 10; i++) {
   // Do something
}

I ask him why but he just said "it's a tip". Can someone give me some explications ?

I have short code below (one for initializing the iterator variable inside the for loop, one for out of for loop). Can you tell me what is better ?

int i = 0;
for (i = 0; i < 10; i++) {
   // Do something
}

for (i = 0; i < 100,; i++) {
   // Do something
}

// Do something, but don't need to use variable `i`

another one:

for (int i = 0; i < 10; i++) {
   // Do something
}

for (int i = 0; i < 100,; i++) {
   // Do something
}

I known that, when declare the iterator inside of for loop, it is limited in the scope of for loop. Are there something important in two cases ?

like image 487
Hitokiri Avatar asked Jun 16 '26 16:06

Hitokiri


1 Answers

As a general rule, the best practice is to declare the variable in the for loop. It avoids confusion and gives the compiler more opportunities for optimization.

The only time to declare in an outer scope is if you need to use the variable again - say loop until you hit a certain criterion, then pick up from where you left off in another loop.

Historically, there was an issue here, in that before standardization of the language, different compilers would treat the scope of the loop iterator differently.

In the following code it would vary where i goes out of scope:

void func(void)
{
    for (int i = 0; i < 10; ++i)
    {
        ...
    } // Some compilers have i going out of scope on the last loop iteration

    int j = i;  // So in some compilers this is valid, others not
} // Other compilers i goes out of scope here

Thus it was more portable to write:

void func(void)    
{
    int i;

    for (i = 0; i < 10; ++i)
    {
        ...
    } 

    int j = i;  // Valid on all compilers
} //  i goes out of scope here on all compilers

Because declaring your loop counter early was more portable. But this was standardized to being the tigther scope back in the 90s, so it's not really an issue now.

like image 82
Jasper Kent Avatar answered Jun 21 '26 10:06

Jasper Kent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!