Why can't you declare variables without curly braces in C++ switch-case?
Hi everyone! I just started learning C++ after Python, and I encountered a strange problem. When I write a regular switch-case, the compiler complains about declaring variables inside case. Here's an example code that doesn't work for me:
```cpp
#include
int main() {
int value = 2;
switch (value) {
case 1:
int x = 10; // Error!
std::cout << "Case 1: " << x << std::endl;
break;
case 2:
int y = 20; // Also error!
std::cout << "Case 2: " << y << std::endl;
break;
default:
std::cout << "Default" << std::endl;
}
return 0;
}
```
The compiler (GCC) gives errors like "jump to case label" and "crosses initialization of variable". I understand that switch
No answers yet.
Log in to leave an answer
Blogs