Why can't variables be initialized in a switch statement?

Overview

We can initialize the variables in the switch statement. But in order to initialize the variables in the switch statement we have to initialize the variable in the new scope of the switch statement. If we try to initialize the variable without a new scope we might get the error that jumping to a case label is the same as using the goto statement. We cannot go to the initialization of a local variable while we are still in the same scope.

Let’s have a look at the example to understand this concept.

Declare a variable in scope

In this example we are going to declare the variable inside the scope of a switch statement.

#include<iostream>
using namespace std;
int main()
{
int i = 2;
switch(i)
{
case 1:
cout<<"Basic Example" <<endl;
break;
case 2:
int x = 21;
cout << x;
break;
}
return 0;
}

Explanation

  • Line 5: Initialize a variable.

  • Line 6-10: We have made a switch statement where it’s first case just prints a statement.

  • Line 12-14: Here in case 2, we are declaring a variable and then printing the value of that variable.

Declare a variable out of scope

In this example we are declaring the variable in one case and then trying to print it’s value in another case.

#include<iostream>
using namespace std;
int main()
{
int i = 2;
switch(i)
{
case 1:
int y = 10;
cout << y;
break;
case 2:
cout << y;
break;
}
return 0;
}

Explanation

  • Line 5: Initializing a variable.

  • Line 8-11: Here in case 1 we are initializing a variable y and then printing it’s value.

  • Line 12-15: Here in case 2 we are just printing the value of y.

Here, we can see that we get a crosses initialization error as there is no separate block in the switch statement that qualifies the declaration period of the y variable. The scope of the variable is limited to the end of the switch statement. So, the compiler reports an error that states that they are not sure whether this variable will be used in other cases and whether it was initialized before its use. For example, if the i variable has the value 2 and is executed directly, an exception is caused due to an undefined variable. Therefore, it causes the crosses initialization compiler error.

Declare a variable in both cases

In this example we are trying to declare the same variable in both the cases.

#include<iostream>
using namespace std;
int main()
{
int i = 2;
switch(i)
{
case 1:
int y = 10;
cout << y;
break;
case 2:
int y = 20;
break;
}
return 0;
}

Explanation

  • Line 5: Initializing a variable.

  • Line 8-11: Here in case 1 we are initializing a variable y and then printing it’s value.

  • Line 12-15: Here in case 2 we are initializing again the value of y.

In this example, we can see that we get the redeclaration error because we initialize the value of y in case 1 and also try to initialize the value of y in case 2.

Free Resources