+ 2
Why output 17 ?
Code : #include <iostream> using namespace std; int main() { int x = 3 ; switch (x) { case 1: {x+=x;} case 3: {x+=x;} case 5: {x+=x;} default: {x+=5;} } cout << x; return 0; } /* Output : 17 */ Someone please explain me why the output is 17 ? Thanks alot !
6 Antworten
+ 12
Well.. this is C++ and in C++ the switch-case statements needs to use break statements in order to not continue running all the cases after the first case that equal the variable in the switch.
Taking your code.. there are not break statements in the cases... so as x=3.. the x+=x will run two times plus the default statement __once for case 3: {x+=x;}, once for case 5: {x+=x;} and lastly the default: {x+=5;}__... and this will happend:
1.- As x=3, x+=x is x=x+x and gets 3+3=6
2.- As now x=6, x+=x gets 6+6=12
3.- As now x=12, the last default statement will get you x+=5 which is x=x+5 and that evaluates 12+5=17
Remember all the code will keep running after the case that is equal to the value on the switch because there are not breaks. If you want the case statement to be executed to be the one equals to the variable value in the switch and nothing more you will have to have something like this:
#include <iostream>
using namespace std;
int main()
{
int x = 3 ;
switch (x) {
case 1: {
x+=x;
break;
}
case 3: {
x+=x;
break;
}
case 5: {
x+=x;
break;
}
default: {
x+=5;
}
}
cout << x;
return 0;
}
/* Output : 6 */
+ 2
Because in switch command every case branch must be ended with the break command.
+ 2
Hatina, Urbuna, Dudnik - thanks for helping me, your answers are very useful .
+ 1
you didn't put break after expressions. that's why case 1 didn't add anything, but after it all cases added values to x. 3+3=6, 6+6=12,12+5=17.
+ 1
put break;
after {x+=x;}
0
use break statement and compile it again