在下面的例子中
void fun() {
if(int i=SOME_VALUE) {
// ...
} else {
// ...
}
}
i 的范围是什么?我们可以在 if block 中使用它吗?我们可以在 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));
}
关于c++ - 在 C++ 中的 if 条件中创建的对象的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18934546/