I wonder why when i use string in swtich statement for example:
1 2 3 4 5 6 7
int i =1;
case 1: string name;
cout << name;
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.
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.
int num = 4;
char a = 'W';
cout << a << endl;
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!
You cannot jump past a declaration with an initializer unless the declaration is enclosed in a block.