Why doesn't string work in switch?

Hi.
I found something weird and I believe you're here to explain it to me.

#include <iostream>
using namespace std;

int a;
cin >> a;
switch (a)
{
case 1:
string str; (here is the first error)
cin >> str;
break;
case 2: (here is the second error)
...

Now it told me:
error: crosses initialization of 'std::string str'
error: jump to case label [-fpermissive]

What I did is I took the "string str;" and put it before the string...
but why did this work and what did the errors actually mean?

Maurycy5
Last edited on
It's a scope issue.

 
string str;


this line does 2 things.

1) It creates a variable named 'str'. This variable has scope (lifetime) until the following closing brace '}'

2) This line also calls the constructor for 'str', which does some memory allocation and initialization of the object.


Now... in your switch statement, if a==2 it will jump to the case label. This is problematic because 'str' will still be in scope (haven't hit a closing brace yet), but you would have skipped passed its initialization. This means the object would be accessible, but not initialized! So it'd be in a bad state. This is extremely dangerous, and could very possibly cause the program to crash even if you never use 'str'.


The solution then, is to either move 'str' outside the switch so that its initialization is never skipped:
1
2
3
4
5
6
7
8
9
10
11
12
int a;
cin >> a;
string str;

switch(a)
{
case 1:
    cin >> str;
    break;

case 2:
    //... 



OR, limit 'str's scope to only the case 1 label by enclosing it in braces:
1
2
3
4
5
6
7
8
9
10
switch(a)
{
case 1:
    {  // <- braces to limit scope
        string str;
        cin >> str;
    }break;

case 2:
    //... 



Either approach will work.
Thank you very much.
I think I quite uderstand what you wanted to tell me.
I don't quite get the mechanism of it all but yeah... thx. see ya! ;)
Topic archived. No new replies allowed.