2

Stumbled upon this gem at work and it looked weird to me, there were {} that was not a part of a if-case or function-definition in the code. I want to remove the extra {} but do not know if they actually do any difference.

This is a small test-program i created to clarify my question. What i am talking about is the extra {} surrounding the "2 hello world" -print below:

#include <stdio.h>

int main()
{
    printf("1 hello world\n");
    {
        printf("2 hello world\n");
    }

    printf("3 hello world\n");

    return 0;
}

The result here is: 1 hello world 2 hello world 3 hello world

So it actually works !

So my question i guess is:

What is the deal with using extra {} in C? I did not expect this to pass the compilation but it worked great.

  • The extra braces make no difference in the example posted, but we can't tell from this if the braces are significant in the actual code found "at work". If there are variable declarations within the new block, then they are significant. Note that a new block may also be established in this way simply to set off code from its surroundings semantically. – ad absurdum Nov 20 '17 at 13:13

1 Answers1

5

What is the deal with using extra {} in C?

It is called block in C. There are four kinds of scopes in C: function, file, block, and function prototype.

C11 6.2.1(P2) Scopes of identifiers:

For each different entity that an identifier designates, the identifier is visible (i.e., can be used) only within a region of program text called its scope. Different entities designated by the same identifier either have different scopes, or are in different name spaces. There are four kinds of scopes: function, file, block, and function prototype. (A function prototype is a declaration of a function that declares the types of its parameters.)

msc
  • 33,420
  • 29
  • 119
  • 214