考虑以下代码:
#include <iostream>
using namespace std;
int main()
{
int x, y, i;
cin >> x >> y >> i;
switch(i) {
case 1:
// int r = x + y; -- OK
int r = 1; // Failed to Compile
cout << r;
break;
case 2:
r = x - y;
cout << r;
break;
};
}
G++ 抱怨:
<source>: In function 'int main()':
<source>:14:14: error: jump to case label
14 | case 2:
| ^
<source>:11:17: note: crosses initialization of 'int r'
11 | int r = 1; // Failed to Compile
| ^
我的问题是:
- What is
crosses initialization
?
- 为什么第一个初始化器
x + y
编译通过,但后者失败?
- 所谓的问题是什么
crosses initialization
?
我知道我应该使用括号来指定范围r
,但我想知道为什么,例如为什么不能在多情况 switch 语句中定义非 POD。
版本与int r = x + y;
也不会编译。
问题是有可能r
进入作用域而不执行其初始化程序。如果您完全删除初始化程序,代码将可以正常编译(即该行将读取int r;
).
您能做的最好的事情就是限制变量的范围。这样你就能同时满足编译器和读者的需求。
switch(i)
{
case 1:
{
int r = 1;
cout << r;
}
break;
case 2:
{
int r = x - y;
cout << r;
}
break;
};
标准说(6.7/3):
可以转移到块中,但不能以绕过初始化声明的方式。从具有自动存储持续时间的局部变量不在范围内的点跳转到其在范围内的点的程序是格式错误的,除非该变量具有 POD 类型 (3.9) 并且在没有初始化程序的情况下声明 (8.5)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)