Why can't c++ define variables after the case? I think this is safe. Suppose int a = 2; this is unsafe, but int a is also unsafe and may go wrong, why the former will report an error, but the latter will not.
#include <iostream>
using namespace std;
int main()
{
int i;
i = 2;
switch (i)
{
case 1:
int j = 10;//Due to initialization, this is not allowed.
j++;
case 2:
j = 20;
cout << j << endl;
case 3:
case 4:
case 5:
default:
break;
}
}
#include <iostream>
using namespace std;
int main()
{
int i;
i = 2;
switch (i)
{
case 1:
int j;//Because there is no initialization, this is allowed.
j = 10;
j++;
case 2:
j = 20;
cout << j << endl;
case 3:
case 4:
case 5:
default:
break;
}
}