Can someone explain this switch-case problem
What is the output of the following code fragment if the input value is 4?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
int num;
int alpha = 10;
cin >> num;
switch (num)
{
case 3:
alpha++;
break;
case 4:
case 6:
alpha = alpha + 3;
case 8:
alpha = alpha + 4;
break;
default:
alpha = alpha + 5;
}
cout << alpha << endl;
A) 13
B) 14
C) 17
D) 22
|
A) 13
B) 14
C) 17
D) 22
I thought it was 13 but the answer is 17, can someone explain because I don't see where the answer comes from.
Last edited on
1 2 3 4 5 6 7
|
case 4:
case 6:
alpha = alpha + 3;
//break;
case 8:
alpha = alpha + 4;
break;
|
Case 8 is also run for 4 and 6.
Is that because there's no break after case 6?
Because you don't have a "break" statement between case 6 and case 8, execution falls through to case 8 and 4 gets added to 13.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
int num;
int alpha = 10;
cin >> num;
switch (num)
{
case 3:
alpha++;
break;
case 4:
case 6:
alpha = alpha + 3;
break;
case 8:
alpha = alpha + 4;
break;
default:
alpha = alpha + 5;
}
cout << alpha << endl;
|
Topic archived. No new replies allowed.