Variables can be declared in the switch statement. You just need to declare them in the switch statement and use them in the new scope. For example,
#include<iostream> using namespace std; int main() { int i = 10; switch(i) { case 2: //some code break; case 10:{ int x = 13; cout << x; } } return 0; }
This will give the output:
13
If you try to declare a variable in a public place, you may get an error , because jumping to a case label is the same as using goto, you are not allowed to skip the declaration of a local variable in the same scope because you may use it elsewhere in the scope.
The above is the detailed content of Why can't variables be declared in the C/C++ switch statement?. For more information, please follow other related articles on the PHP Chinese website!