What is the purpose of anonymous { } blocks in C style languages?

后端 未结 17 1024
囚心锁ツ
囚心锁ツ 2020-11-28 09:34

What is the purpose of anonymous { } blocks in C style languages (C, C++, C#)

Example -



void function()
{

  {
    int i = 0;
    i = i + 1;
  }

          


        
17条回答
  •  离开以前
    2020-11-28 09:38

    One thing to mention is that scope is a compiler controlled phenomenon. Even though the variables go out of scope (and the compiler will call any destructors; POD types are optimised immediately into the code), they are left on the stack and any new variables defined in the parent scope do not overwrite them on gcc or clang (even when compiling with -Ofast). Except it is undefined behaviour to access them via address because the variables have conceptually gone out of scope at the compiler level -- the compiler will stop you accessing them by their identifiers.

    #include 
    int main(void) {
      int* c;
      {
        int b = 5; 
        c=&b;
      }
      printf("%d", *c); //undefined behaviour but prints 5 for reasons stated above
      printf("%d", b); //compiler error, out of scope
      return 0;
    }
    

    Also, for, if and else all precede anonymous blocks aka. compound statements, which either execute one block or the other block based on a condition.

提交回复
热议问题