I wonder why when i use string in swtich statement for example:
1 2 3 4 5 6 7
int i =1;
switch (i)
{
case 1: string name;
cin>> name;
cout << name;
break;
i get an error message like this:
initialization of 'name' is skipped by 'case' label
see declaration of 'name'
i figured out that all i have to do is to put opening curly bracket after case 1: and closing after break and it work fine.. but why.
what is the problem and is there any other way to prevent of error??
The problem is the scope of the local variable. The variable name is still within scope throughout the rest of the switch statement. But if one of the other cases is executed, the variable will not have been properly constructed.
You found one solution, which is to use braces to limit the scope. The alternative would be to move the definition of the variable outside the body of the switch statement. Generally, it would be preferred to limit the scope of the variable to the part of the code where it is needed, so the first solution might be better. But the context and what the code is trying to achieve would influence the decision.
switch is doing the same kind of thing with a little different syntax. It is jumping to a label. Consider this coding atrocity that actually builds with my compiler:
Since jumping to labels doesn't care one bit about breaching into scope, the compiler is trying to save you some grief by not letting you initialize new variables unless you contain them in a new scope or define them outside the scope of the 'goto'. This will not compile because the "case 4 label" splits the containing scope of inBetweenLabels.
it had been really helpfull. at least now i know why it is so. but then other question pops up in my mind. why it doesn t complain when i use char inside of switch statement. thank you. :)
#include <iostream>
usingnamespace std;
int main()
{
int num = 4;
switch (num)
{
case 1:
char a = 'W';
cout << a << endl;
break;
case 4:
default:
break;
}
return 0;
}
#include <iostream>
usingnamespace std;
int main()
{
int num = 4;
switch (num)
{
case 1:
char a;
a = 'W';
cout << a << endl;
break;
case 4:
default:
break;
}
return 0;
}
#include <iostream>
usingnamespace std;
int main()
{
int num = 4;
switch (num)
{
case 1:
char a = 'W';
cout << a << endl;
break;
case 4:
default:
break;
}
return 0;
}
I'm getting into a place where I don't know the standard well enough to say what is expected behavior or what may be compiler-specific and non-conforming. Weird stuff, guys. Avoid the pothole and create new scope, I guess!
From MSDN:
You cannot jump past a declaration with an initializer unless the declaration is enclosed in a block.