Practical use of extra braces in C

前端 未结 4 653
时光取名叫无心
时光取名叫无心 2021-01-07 11:20

I know {} are used to separate entities such as functions, classes and conditional branching, but what other use would they have here?

#import &         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-07 11:56

    Enclosing a code in braces { } creates an Scope.
    Creating an local scope can have number of reasons like:

    • Allows you to reuse a variable name in enclosing scope.
    • Define variables in middle of function.
      Creating variables anywhere except at the start of an scope was not allowed in c89, but it is allowed since c99.

    Online Example Code Sample:

    #include
    
    int main()
    {
        int i = 10;
        {
             int i = 5;
             printf("i is [%d]\n",i);
        }
        printf("i is [%d]\n",i);
    
        return 0; 
    }
    

    In your example code,
    the extra { & } do not serve any purpose, they are just redundant code.

    As @Martin suggests in comments, since enclosing code in {{{ & }}} is just similar to { & }, it might be used as an tag/pattern for easy search.

    However, Personally, I would prefer adding appropriate comment to the code with an keyword which would show up in search rather than add such redundant code.

提交回复
热议问题