条件语句后面有多个单独的带括号的代码段

Multiple separate bracketed code segments after a conditional statement

本文关键字:代码 单独 语句 条件      更新时间:2023-10-16

在下面的代码示例中-这是不好的做法吗?为什么编译器进入第二个括号内的语句?奇怪的是,我以前从来没有经历过这种情况,但在一次面试中出现了。我本以为第二个括号段会寻找另一个条件语句。代码如下:

if ( condition )
{
    // some code
}
{
    // some code
}

感谢您提前提供的有帮助的解释

您可以在任何地方使用{}创建块;它不需要附加if条件。

可用于控制对象的生存期。

{
    MyObject foo;
    // ... do something with foo ...
}   // MyObject just went out of scope, so its destructor is called
// foo is no longer defined
if ( condition )
{
    // gets executed if condition == TRUE
}
{
    // always gets executed, has nothing to do with previous if statement
    int a = 42 ; //only exists inside brackets
}