Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Jump to case label" error when using vectors inside switch statement. [duplicate]

This is the code, where I get several errors, when I add the other case or a deafult. I can't find any basic error like a missing semicolon or so, and the code works properly when I have only one case. I searched trough switch tutorials, but I didn't find anything about vectors and switch statements mixed is a problem.

int main()
{
int r; 
while (cin >> r)
{
    switch (r) 
    {
       case 3:
    int y = 0;
    cout << "Please enter some numbers, and I will put them in order." << endl; 
    vector<int> nums;
    int x;
    while(cin >> x)
    {
        nums.push_back(x);
        y++;
    }
    sort(nums.begin(), nums.end());
    int z = 0;
    while(z < y)
    {
        cout << nums[z] << ", ";
        z++;
        if(z > 23)
            cout << "\n" << "User... What r u doin... User... STAHP!" << endl;
    }
    cout << "\n" << "You entered "<< nums.size() << " numbers." << endl;
    cout << "Here you go!" << endl;
    break;

    //In the following line I get the "jump to case label" error. 
    //I use Dev C++ software.

       case 4:
    cout << "it works!!!" << endl;
    break; 
    }
}
system ("PAUSE");
return 0;
}

What am I missing?

like image 238
Attila Herbert Avatar asked Aug 29 '13 17:08

Attila Herbert


People also ask

How do you fix a case label not within a switch statement?

How to fix? See the statement switch(choice); it is terminated by semicolon (;) – it must not be terminated. To fix this error, remove semicolon after this statement.

What does the error jump to case label mean?

The problem is that variables declared in one case are still visible in the subsequent case s unless an explicit { } block is used, but they will not be initialized because the initialization code belongs to another case .

Which type of case label can be used with switch statement?

A case or default label can only appear inside a switch statement. The constant-expression in each case label is converted to a constant value that's the same type as condition . Then, it's compared with condition for equality.

Can a switch statement have no cases?

The switch statement can include any number of case instances. However, no two constant-expression values within the same switch statement can have the same value.


1 Answers

Add another scope inside the case:

switch(n) 
{
case 1:
    {
        std::vector<int> foo;
        // ...
        break;
    }
case 2:
    // ...
default:
    // ...
}

The extra scope constrains the lifetime of the vector object. Without it, a jump to case 2 would skip over the initialization of the object, which would nonetheless have to be destroyed later, and this is illegal.

like image 192
Kerrek SB Avatar answered Sep 19 '22 05:09

Kerrek SB