在浏览我 friend 的代码时,我注意到了这一点:
switch(State &state = getState()) {
case Begin: state = Search; break;
// other stuff similar
}
switch header 中的变量是什么?他正在使用 GCC,所以我认为这可能是 GCC 扩展。有什么想法吗?
最佳答案
这不是 secret 或 GCC 扩展。允许在 if
、while
和 switch
等条件中声明变量。例如:
while (char c = cin.get()) { ... }
或
if (int* something = (int*)malloc(4)) { // but don't use malloc in C++
// ...
}
在它们被声明为初始化后,它们被转换为 bool
值,如果它们的计算结果为 true
,则执行该 block ,否则跳过该 block 。它们的范围是声明它们的条件的构造的范围(在 if
的情况下,范围也涵盖所有 else if
和 else
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-expression
在 if
或 switch
的条件下.您会在“重复构造”部分找到类似内容。
此外,switch
es 可以在整数或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/