以前没有任何关键字的{}的目的是什么

What is the purpose of {} without any keyword before?

本文关键字:是什么 关键字 任何      更新时间:2023-10-16

今天,我花了4个小时调试了一个小错误:

while (++i < nb); //Notice this semicolon that i put by mistake
{
    do_stuff();
}

我不知道do_stuff为什么没有执行足够的次数。当我看到我的错误时,我想知道:为什么有人会把代码放在函数中间的大括号里??有人能解释一下吗?C语言就是这样进化的吗?(我知道由于复古兼容性的原因,C的BNF包含了一些奇怪的东西)你认为循环中的预增是件坏事吗?我应该像上面那样写?

while (i < nb)
{
    do_stuff();
    i += 1;
}

为什么有人会把代码放在函数中间的大括号里??

这一点都不奇怪,但它引入了一个范围,如以下示例所示:

void foo () {
    int a;
    {          // start a new scope
        int b = 1;
        std::cout << b << std::endl;
    }         // end of scope, i.e. b is out of scope now
    std::cout << a << std::endl;
    std::cout << b << std::endl; // error: unknown variable b !!
    double b = 0.0;              // just fine: declares a new variable
}

您可以使用它来本地化函数内部变量的可访问性。在示例中,b是一个临时的,通过将其声明放在本地作用域中,我可以避免在函数作用域中滥发变量名。

您可能希望将所有逻辑都放在while中,并有意省略body。一些编译器会警告你这一点,比如clang:

main.cpp:18:17: warning: while loop has empty body [-Wempty-body]
while (++i < nb); //Notice this semicolon that i put by mistake
                ^
main.cpp:18:17: note: put the semicolon on a separate line to silence this warning

引入本地作用域,如:

{
   SomeClass aa;
   // some logic
}

你可能希望,在上面的例子中,有人可能希望在大括号之前调用一个析构函数,也就是说,它会释放一些资源。

我相信最常见的用途是与RAII:一起使用

{
   std::lock_guard<std::mutex> lock(mutex);
   // code inside block is under mutex lock
}
// here mutex is released

本地作用域有意义限制对象的生存时间和作用域。它们对switch/case语句至关重要:

switch (i){
case 1:
    std::string s;
case 2:
    //does s exist or not? depends on the value of i
}

C++说这是直接非法的。为了解决这个问题,你引入了一个本地作用域:

switch (i){
case 1:
{
    std::string s;
}//the lifetime of s ends here
case 2:
    //s is inaccessible
}

现在s被限制在它的范围内,并且您解决了s有时被定义的问题。

您可以添加任意数量的本地块,例如,这很好:

int main(){{{{{{{{{{
}}}}}}}}}}

{<statement>*}(*表示零或更多)是C/C++中的代码块,被视为单个语句。语句类似于if (<expression>) <statement>(注意:这是一个递归语句)。另一个语句可以是<expression>;

此外,{}生成一个新的作用域。

这也是为什么可以在if语句中给出多个语句的原因。

如果有帮助,您可以将它们视为内联函数,并可以访问当前范围。(不是正确的查看方式,但距离足够近)

看看@tobi303的回答作为一个例子。