Why enclose blocks of C code in curly braces?

Legacy code needed { } in order to do declarations at all

In C89, you couldn't just do int i; anywhere; declarations were only valid at the beginning of blocks.

So:

a = 1;
int i; /* error */
i = 2;

...wasn't valid, but

a = 1
if (e) {
  int i;

...was fine, as was a plain block.

The resulting style continued even after declarations became valid (C99) block-item(s), partly by inertia, partly for backwards portability, and also because it makes sense to establish a scope for new declarations.


To scope variables. E.g. the variable tmp_argv will only be valid between the braces.


Another use case for this I've recently discovered is when you have open/close semantics and you want to clearly mark the 'inner' code:

f = fopen('file');
{
    // do stuff
}
fclose(f);

This works well to remind you to close/free objects and a makes the code somewhat cleaner.