Home > Back-end >  Best behavior in C: for loop variables locally or globally defined
Best behavior in C: for loop variables locally or globally defined

Time:01-12

Which is considered the best behavior in C and what are the pros cons of the two possible following options?

OPTION 1 (global variable):

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

OPTION 2 (local variable):

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

EDIT: Assume I don't need the variable after looping over it.

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • Related