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

后端 未结 17 923
囚心锁ツ
囚心锁ツ 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
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 09:54

    You are doing two things.

    1. You are forcing a scope restriction on the variables in that block.
    2. You are enabling sibling code blocks to use the same variable names.
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 10:00

    It's about the scope, it refers to the visibility of variables and methods in one part of a program to another part of that program, consider this example:

    int a=25;
    int b=30;
    { //at this point, a=25, b=30
         a*=2; //a=50, b=30
         b /= 2; //a=50,b=15
         int a = b*b; //a=225,b=15  <--- this new a it's
                      //                 declared on the inner scope
    }
    //a = 50, b = 15
    
    0 讨论(0)
提交回复
热议问题