Best behavior in C: for loop variables locally or globally defined

The main benefit of option 1 is that you can use x outside the body of the loop; this matters if your loop exits early because of an error condition or something and you want to find which iteration it happened on. It's also valid in all versions of C from K&R onward.

The main benefit of option 2 is that it limits the scope of x to the loop body - this allows you to reuse x in different loops for different purposes (with potentially different types) - whether this counts as good style or not I will leave for others to argue:

for ( int x = 0; x < 100; x++ )
  // do something

for ( size_t x = 0; x < sizeof blah; x++ )
  // do something;

for ( double x = 0.0; x < 1.0; x += 0.0625 )
  // do something

However, this feature was introduced with C99, so it won't work with C89 or K&R implementations.


This is not an answer. This is a third option, that is sort of intermediate:

{
    int x;
    for (x = 0; x < 100; x++) {
        // do something
    }
    // use x
}

This is equivalent to the 2nd option, if there's no code between the two closing brackets.