为什么在C++中不能在switch块内不加大括号声明变量?
大家好!我开始学习C++,在使用switch时遇到了一个非常奇怪的错误。我需要编写一个简单的计算器,根据输入的字符执行不同的操作。这是我的代码:
```cpp
#include
using namespace std;
int main() {
char op;
int a = 10, b = 5;
cout << "Enter operation (+, -, *, /): ";
cin >> op;
switch (op) {
case '+':
int result = a + b; // 错误!
cout << result;
break;
case '-':
// ...
break;
}
return 0;
}
```
编译器报错:"cannot jump from switch statement to this case label" 或者类似 "initialization of 'result' is skipped by 'case' label"。我知道switch像goto一样工作,跳转到对应的标签,但为什么不能在case内部直接声明变量呢?我明明是在冒号后面、break之前写的。问题出在哪里,以及如何正确声明变量?