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.

Leave a Comment