It creates a scope. Are there automatic variables inside blocks? If so, then the scope of these variables is limited to a block. This is useful for temporary variables that you don’t want to pollute the rest of the function, and also useful when writing C89, where the variable definitions should be at the beginning of the block.
So, instead of:
int main() { int a = 0; int b; int i; for (i = 1; i < 10; ++i) { a += i; } b = a * a;
You may have:
int main() { int a = 0; { int i; for (i = 1; i < 10; ++i) { a += i; } } { int b = a * a;
Obviously, if you do this, you also need to ask yourself if the blocks would be better used as separate functions.
Steve jessop
source share