gpt4 book ai didi

c++ - C++ 何时引入了在 if 语句中声明变量的功能?

转载 作者:行者123 更新时间:2023-12-02 18:39:21 27 4
gpt4 key购买 nike

在C++中,我们可以直接在if语句中声明变量,并将其值作为条件,例如

if (SubClass *subObject = dynamic_cast<SubClass *>(baseObject)) {
// ...
}

出于某种原因,我一直认为这是一个“相对”新的特性,最早是在 C++11 中引入的,但是当我试图证实这一点时,我没有找到任何关于此的信息,只发现 C++ 17 进一步扩展了语法。当我尝试使用 -std=c++98 编译一个最小示例时,它起作用了。那么这从一开始就是 C++ 的一个特性吗?

最佳答案

第一个正式 C++ 标准是 ISO/IEC 14882:1998(又名 C++98)。在 this 'draft' version of that中,明确提到了 if 语句内变量的声明:

6.4 Selection statements       [stmt.select]



3     A nameintroduced by a declaration in a condition (either introduced by thetype-specifier-seq or the declarator of the condition) is in scopefrom its point of declaration until the end of the substatementscontrolled by the condition. If the name is re-declared in theoutermost block of a substatement controlled by the condition, thedeclaration that re-declares the name is ill-formed. [Example:

if (int x = f()) {
int x; // ill-formed, redeclaration of x
} else {
int x; // ill-formed, redeclaration of x
}

—end example]

所以,就正式标准而言:是的,它“从一开始就存在。”

关于c++ - C++ 何时引入了在 if 语句中声明变量的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68254736/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com