c++ - 开关头中的变量声明?

标签 c++

在浏览我 friend 的代码时,我注意到了这一点:

switch(State &state = getState()) {
case Begin: state = Search; break;
// other stuff similar
}

switch header 中的变量是什么?他正在使用 GCC,所以我认为这可能是 GCC 扩展。有什么想法吗?

最佳答案

这不是 secret 或 GCC 扩展。允许在 ifwhileswitch 等条件中声明变量。例如:

while (char c = cin.get()) { ... }

if (int* something = (int*)malloc(4)) { // but don't use malloc in C++
    // ...
}

在它们被声明为初始化后,它们被转换为 bool 值,如果它们的计算结果为 true,则执行该 block ,否则跳过该 block 。它们的范围是声明它们的条件的构造的范围(在 if 的情况下,范围也涵盖所有 else ifelse block )。

在 C++03 标准的 §6.4.1 中,它说

Selection statements choose one of several flows of control.

selection-statement:

    if ( condition ) statement
    if ( condition ) statement else statement
    switch ( condition ) statement

condition:

    expression
    type-specifier-seq declarator = assignment-expression

如您所见,它允许 type-specifier-seq declarator = assignment-expressionifswitch 的条件下.您会在“重复构造”部分找到类似内容。

此外,switches 可以在整数或enum 类型上工作可以隐式转换为整数或的类的实例枚举类型(§6.4.4):

The value of a condition that is an initialized declaration in a switch statement is the value of the declared variable if it has integral or enumeration type, or of that variable implicitly converted to integral or enumeration type otherwise.

我居然知道了这个FROM AN ANSWER YOU POSTED关于“C++ 的隐藏特性”问题。所以我很高兴能提醒你 :)

关于c++ - 开关头中的变量声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10365901/

相关文章:

c++ - 如何重用函数专门化代码?

C++ - 将一个 ostream 中的数据发送到另一个 ostream

c++ - 检测按键按下和按键释放事件

c++ - 以编程方式获取 powershell.exe 的完整路径

c++ - 如何处理clang中的 "exit-time destructor"警告?

用于搜索和替换的 C++ 设计模式

c++ - 如何重载继承类中的方法,以便基类看到继承的版本?

c++ - 仅扩展 QGridLayout 中的一列

c++ - 处理重构、模板 SFINAE 测试和 lambda

c++ - 使用 cin.getline() 后清除 cin 缓冲区时出现问题