Automatic variables are local to a region in C:
The scope is basically labeled '{' '}', so when you are inside the pair {}, you are inside the scope. Of course, areas can be nested.
This is why in the earlier C standard, local variables had to be defined at the top of the scope, because it made it easier for the C compiler to write (the compiler would see "{" and then all the variables and then the instructions), so he knew the variables with which he had to deal. This has changed in C99 (I think?), And later, where you can define variables anywhere between statements.
Of course, this can be useful:
int foo() { int k = 0; for(; k < 10; k++) { int i = 1; i = i * 2; printf ("k = %d, i = %d\n", k, i); } #if 0 printf ("i = %d\n", i); #endif return 0; } int main() { foo(); foo(); return 0; }
Note that I = 2 all the time for loop iterations in foo ()
It's even more interesting to see how the static changes the persistence of a variable.
int bar() { int k = 0; for(; k < 10; k++) { static int i = 1; i = i * 2; printf ("k = %d, i = %d\n", k, i); } #if 0 printf ("i = %d\n", i); #endif return 0; } int main() { foo(); foo(); return 0; }
Notice the changes and notice how the static variable is handled.
What happens to the for loop if you put the static keyword before int k = 0 ;?
Interesting use
Macros
C is very useful. Sometimes you want to define a complex local macro rather than a function for speed and overall simplicity. In the project, I wanted to manipulate large bitmaps, but using functions to perform "and" or "xor" operations was a little painful. The size of the bitmaps was fixed, so I created several macros:
#define BMPOR(m1, m2) do { \ int j; \ for (j = 0; j < sizeof(bitmap_t); j++ ) \ ((char *)(m1))[j] |= ((char *)(m2))[j]; \ } while (0)
do {} while (0) - a funny trick to associate a block with binding to if / for / while, etc. without a problem, the block is executed exactly once (since while is checked in the END block), and when the compiler sees while (0), it simply removes the loop; and, of course, this allows you to put a half-year at the end so that the IDE and you (later) do not get confused about what it is.
The macro above was used as:
int foo() { bitmap_t map_a = some_map(), map_b = some_other_map(); BITOR(map_a, map_b); }
here do {} while (0) allows a local scope with local variable j, a for loop, and all that I might need.