Search code examples
cscopecurly-braces

Is this practice of manually applying scopes standard C?


Is creating local scopes with just a pair of brackets, would that be considered standard C?

#include <stdio.h>

int main(int argc, char *argv[]) {
    {
        register char x = 'a';
        putchar(x); // works
    }
    //putchar(x); wont work
}

Or is it best to not use this? Is it a GCC compiler extension?

I have once been told that the accepted practice is a do {...} while (0); loop. Is it true that all C compilers will recognise this practice just like it is safe to assume any given C compiler will recognise an if statement?

I tried googling this, and my results were about scope behavior, and had nothing to do with manually applying scopes.


Solution

  • Yes, it is standard; this is creation of block scope, as supported by C language.

    Regarding "best to use" part, it depends, certainly it might be a bit confusing to some people.

    This might come in very useful with generated code though, so you don't need to bother (as much) with unique identifiers for local vars:

    int main(int argc, char *argv[]) {
      {
        int x = 4;
        printf("%d\n", x);
      }
      {
        int x = 5;
        printf("%d\n", x);
      }
    }