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

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

    They are often useful for RAII purposes, which means that a given resource will be released when the object goes out of scope. For example:

    void function()
    {
        {
            std::ofstream out( "file.txt" );
            out << "some data\n";
        }
        // You can be sure that "out" is closed here
    }
    

提交回复
热议问题