S
subramanian100in
Consider the following program:
#include <iostream>
using namespace std;
int main()
{
int i;
cin >> i;
switch ( i )
{
case 1:
int case_1 = 1;
cout << "case_1 " << case_1 << endl;
break;
case 2:
int case_2 = 2;
cout << "case_2 " << case_2 << endl;
break;
}
return 0;
}
If a variable is declared inside any case label except the last case
label, I am getting compilation error. In this program I am getting
compilation error for the declaration
int case_1 = 1;
inside case 1.
But there is no compilation error for the declaration
int case_2 = 2;
inside case 2.
Kindly explain what is the difference and why is the declaration not
allowed in other case labels but allowed in the last case label in a
switch ?
#include <iostream>
using namespace std;
int main()
{
int i;
cin >> i;
switch ( i )
{
case 1:
int case_1 = 1;
cout << "case_1 " << case_1 << endl;
break;
case 2:
int case_2 = 2;
cout << "case_2 " << case_2 << endl;
break;
}
return 0;
}
If a variable is declared inside any case label except the last case
label, I am getting compilation error. In this program I am getting
compilation error for the declaration
int case_1 = 1;
inside case 1.
But there is no compilation error for the declaration
int case_2 = 2;
inside case 2.
Kindly explain what is the difference and why is the declaration not
allowed in other case labels but allowed in the last case label in a
switch ?