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.
Answer from John Bode on Stack OverflowVideos
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.
As the title states, really. Is there a "preferred" practice of how you declare your variables, or is it all just personal preference?
For instance I currently have a lot of global variables in my code, but they're all used all over the place in many different functions so to me it makes sense for the majority of them to be global. Also, my code is for embedded systems.
From what I can see though, people seem to think it's better to use local variables over global variables, even though this would surely take tons of re declaring and complex function arguments to keep variables across multiple functions.
Am I just not thinking about this the right way? Are there pros and cons of both global and local variables?
Edit: Forgot to mention that the C code is used in Atmel uC's, and is Embedded.