Why can't I declare a variable in the switch statement?

Asked 2 years ago, Updated 2 years ago, 30 views

I thought C++ could declare a variable anywhere Why can't you declare a variable in the switch statement?

switch (val)
{
    case 1:
        int newVal = 42;
        break;
    case 2:
        break;
}

c c++ switch문

2022-09-21 18:36

1 Answers

Specifying a case in switch-case is to set label This label is used by the compiler to jump to label corresponding to val.

The problem with the above code starts with {} bundling all the codes in the switch statement into one scope. When a block is started, space is allocated to memory for local variables In the above code, if val is not 1, the part that initializes newVal will not be executed, resulting in an error.

This is because there is only one {} in the switch statement If you specify a scope for each case, you can declare a variable inside the switch door

switch (val)
{   
    case 1:  
    {
        int newVal = 42;  
        break;
    }
    case 2:
        break;
    }
}


2022-09-21 18:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.