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

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

    A useful use-cas ihmo is defining critical sections in C++. e.g.:

    int MyClass::foo()
    {    
       // stuff uncritical for multithreading
       ...
       {
          someKindOfScopeLock lock(&mutexForThisCriticalResource);
          // stuff critical for multithreading!
       }
       // stuff uncritical for multithreading
       ...    
    }
    

    using anonymous scope there is no need calling lock/unlock of a mutex or a semaphore explicitly.

提交回复
热议问题