Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of lone curly-braced code blocks in C

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...

like image 525
user17925 Avatar asked Sep 03 '10 14:09

user17925


3 Answers

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.

like image 174
Steve Jessop Avatar answered Oct 21 '22 05:10

Steve Jessop


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

like image 23
Mark Cidade Avatar answered Oct 21 '22 04:10

Mark Cidade


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
like image 26
Péter Török Avatar answered Oct 21 '22 04:10

Péter Török