在 C++ 中的 if 条件中创建的对象的范围

Scope of an object created in an if-condition in C++

本文关键字:创建 对象 范围 条件 C++ 中的 if      更新时间:2023-10-16

在下面的示例中

void fun() {
    if(int i=SOME_VALUE) {
        // ...
    } else {
        // ...
    }
}

i的范围是什么?我们可以在 if 块中使用它吗?我们可以在 else-block 中使用它吗?

编辑:

作为后续,在此修改后的示例中

void fun() {
    if(int i=SOME_VALUE) {
        // ...
    } else if(int j=SOME_OTHER_VALUE){
        // ...
    } else {
        // ...
    }
}

我们可以在 else 子句中同时访问 i 和 j 吗?

是的,是的。

其典型用途是动态强制转换:

if (auto p = dynamic_cast<Derived*>(base_pointer))
{
    // p is a Derived*
}
else
{
    // not the right dynamic type
}

我发现另一个有用的结构:

if (auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(std::fopen("file.txt", "rb"), std::fclose))
{
    // file exists, use fp.get()
}
else
{
    // file does not exist
}

还有一个:

if (pid_t pid = fork())
{
    waitpid(pid, nullptr, 0);
}
else
{
    execl("/bin/rm", "/bin/rm", "-rf", "/", static_cast<char*>(nullptr));
}

是的,您可以使用在 else 子语句的 if 条件中声明的变量,就像您的示例一样。

但是,如果在 if 子语句中声明i,如下所示:

if (some_condition) {
    int i = 42;
    // ...
} else {
    std::cout << i;  //error
    // ...
}

else部分中,变量 i 不再在范围内。

是的,因为变量是在最外层范围内"创建"的,然后才在if条件下进行评估。您的代码可以重写如下:

int i = SOME_VALUE;
if(i) {
    // ...
} else {
    // ...
}

而不是像:

if(SOME_VALUE) {
    int i = SOME_VALUE;
    // ...
} else {
    // ...
}

正如你可能有的那样。

第二个问题可以用同样的方式回答。