0
C++ challenge switch and arrays
Hi there. I found this question as a challenge and I don't get the output... int x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int y : x) { switch(y) { case 1: cout << "C"; case 3: cout << "P"; case 7: cout << "P"; case 8: cout << "!"; } } Output is: CPP!PP!P!! But why? My solution would be CPP! I just don't get it...
2 Answers
+ 1
For every number 'y' in array x, the complete switch is gone through.
So for 1, it's 'CPP!', because the breaks are missing ('fall-through').
2 is ignored since there is no case 2.
3 starts with case 3 and falls through from there: 'PP!'
And so on.
+ 1
Thanks!