Practical use of extra braces in C

前端 未结 4 633
时光取名叫无心
时光取名叫无心 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条回答
  •  萌比男神i
    2021-01-07 11:49

    Extra braces gives you scope as Als mentioned. This can be used in case of Smart Pointers effectively. e.g., consider the following code in C++ (MSVC compiler)

    int i = 0;
    i++;
    //More code follows 
    ...
    
    {
        CComBSTR bstr("Hello");
        //use this bstr in some code
        .....
    }
    

    After the end braces, bstr won't be available. Furthermore, since it has gone out of scope, therefore, the destructor will also get called automatically.

提交回复
热议问题