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

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

    By creating a new scope they can be used to define local variables in a switch statement.

    e.g.

    switch (i)
    {
        case 0 :
            int j = 0;   // error!
            break;
    

    vs.

    switch (i)
    {
        case 0 :
        {
            int j = 0;   // ok!
        }
        break;
    

提交回复
热议问题