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

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

    It limits the scope of variables to the block inside the { }.

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

    Scoping of course. (Has that horse been beaten to death yet?)

    But if you look at the language definition, you see patterns like:

    • if ( expression )   statement
    • if ( expression )   statement   else   statement
    • switch ( expression )   statement
    • while ( expression )   statement
    • do   statement   while ( expression ) ;

    It simplifies the language syntax that compound-statement is just one of several possible statement's.


    compound-statement:   { statement-listopt }

    statement-list:

    • statement
    • statement-list   statement

    statement:

    • labeled-statement
    • expression-statement
    • compound-statement
    • selection-statement
    • iteration-statement
    • jump-statement
    • declaration-statement
    • try-block
    0 讨论(0)
  • 2020-11-28 09:36

    I use it for blocks of code that need temporary variables.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-11-28 09:38

    As far as I understand, they are simply for scoping. They allow you to reuse variable names in the parent/sibling scopes, which can be useful from time to time.

    EDIT: This question has in fact been answered on another Stack Overflow question. Hope that helps.

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

    As the previous posters mentioned, it limits the use of a variable to the scope in which it is declared.

    In garbage collected languages such as C# and Java, it also allows the garbage collector to reclaim memory used by any variables used within the scope (although setting the variables to null would have the same effect).

    {
        int[] myArray = new int[1000];
        ... // Do some work
    }
    // The garbage collector can now reclaim the memory used by myArray
    
    0 讨论(0)
提交回复
热议问题