views:

213

answers:

5

I've come across a bit of code that contains a couple code blocks, delineated with curly braces {}. There is no line before the code blocks marking them as part of if statements, function definitions, or anything else. Just a code block floating in the middle of a function. Is there any meaning to this? gcc seems perfectly happy going through the code; I can only imagine it is some way to allow the original coder to split up blocks of functionality visually...

+10  A: 

It creates a scope. Are there automatic variables defined inside the blocks? If so, then the scope of those variables is confined to the block. It's useful for temporary variables that you don't want polluting the rest of the function, and it's also useful when writing C89, where variable definitions must be at the start of a block.

So, instead of:

int main() {
    int a = 0;
    int b;
    int i;

    for (i = 1; i < 10; ++i) {
        a += i;
    }

    b = a * a;
    // do something with a and b
}

You could have:

int main() {
    int a = 0;
    {
        int i;
        for (i = 1; i < 10; ++i) {
            a += i;
        }
    }

    {
        int b = a * a;
        // do something with a and b
    }
}

Obviously if you're doing this, you also have to ask yourself if the blocks wouldn't be better off as separate functions.

Steve Jessop
+1 for examples and some discussion of *why* someone would use scoping.
Edmund
+2  A: 

If the code blocks contain local variable declarations (your description is not clear about what's inside), they may be there to limit the scope of those variables. I.e.

int i = ...;
// i is visible here
{
  int j = ...;
  // both i and j are visible here
}
// j went out of scope, only i is visible here
Péter Török
+9  A: 

Standalone curly braces are used for scoping—any variables declared in a block aren't visible outside it.

Mark Cidade
This is a very powerful tool in C++ when combined with RAII.
krousey
A: 

It usually means it was written to declare a variable part way through a larger function, but the variable only needs a very limited scope, or may even need to hide something. It is entirely legimitate - it simply introduces a block. The big issue is always "what is the correct indentation for that code".

It can also be used by pre-processors that convert some other language into generated C. The converted material is often wrapped in a block (and possibly #line directives too).

Jonathan Leffler
+2  A: 

It is used to create a scope. A scope if useful to declare variables that can only be used inside this scope. For example, if a variable is declared before the braces, it can be used inside the braces of after them. At the contrary, if a variable is declared inside the braces, it can only be used inside the braces. Hope this helps.

Live