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

后端 未结 17 1066
囚心锁ツ
囚心锁ツ 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:58

    They're very often used for scoping variables, so that variables are local to an arbitrary block defined by the braces. In your example, the variables i and k aren't accessible outside of their enclosing braces so they can't be modified in any sneaky ways, and that those variable names can be re-used elsewhere in your code. Another benefit to using braces to create local scope like this is that in languages with garbage collection, the garbage collector knows that it's safe to clean up out-of-scope variables. That's not available in C/C++, but I believe that it should be in C#.

    One simple way to think about it is that the braces define an atomic piece of code, kind of like a namespace, function or method, but without having to actually create a namespace, function or method.

提交回复
热议问题