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

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

    Brackets designate an area of scope - anything declared within the brackets is invisible outside of them.

    Furthermore, in C++ an object allocated on the stack (e.g. without the use of 'new') will be destructed when it goes out of scope.

    In some cases it can also be a way to highlight a particular piece of a function that the author feels is worthy of attention for people looking at the source. Whether this is a good use or not is debatable, but I have seen it done.

提交回复
热议问题