The issue of variable declaration in switch
-case
statements is well discussed in this SO post, and the answers covered most of the aspects. But I faced a problem for that I couldn't find a solid reason. Can someone please explain what is wrong with this code?
switch (var)
{
case 0:
int test;
test = 0; // no error
int test2 = 0; // ERROR: initialization of 'test2' is skipped by 'case' label
std::string str;
str = "test"; // ERROR: initialization of 'str' is skipped by 'case' label
break;
case 1:;
break;
}
I know why the 6th line results in error. But what is wrong with the next two lines? I think this may have something to do with the difference between native types and class types, but I am not sure.
This is not a duplicate question of Why can't variables be declared in a switch statement?! As I have provided a link to the original one. Please read the two questions and note the difference. AFAIK, issue is not discussed in the original question.