+ 1
How 17 is coming as an answer?
9 odpowiedzi
+ 7
Krishna Kumar Everything from the first matching case to the next break statement is executed, if there isn't a break statement then it will execute everything until the end of the switch block
+ 7
After each case you must put a break. Otherwise program go thought other cases:
case 1:
x += x;
break;
In your case it enters in case 3 and all the sums are performed:
case 1:{x+=x;}; // sums 6
case 3:{x+=x;}; // sums 9
case 5:{x+=x;}; // sums 12
default :{x+=5;}; // sums 17
Right code is:
case 1:{x+=x;};
break;
case 3:{x+=x;}; // sums 6
break; // stops here. go out switch
case 5:{x+=x;};
break;
default :{x+=5;};
break;
+ 5
You're right Anna. It starts in case 3
+ 4
Because there is no break, so three code blocks get executed, including under case 3 case 5 and default.
+ 4
Javier Felipe Toribio 98.2% correct, but case 1 won't be executed.
It's case 3: x += x (x is now 6)
case 5: x += x (x is now 12)
default: x += x (x is now 17)
+ 2
Wow, Anna, you are so accurate in calculating the correct percentage of Javier's answer. The precision is even to one decimal place. I am impressed~
+ 2
Thanks Anna.
+ 1
Like case 1 is ignored (being an unmatched case), then why case 5 and default are not ignored (one being unmatched and other being dafault when no catch is matched)?
+ 1
Because you need to use
break;
statement to get out of the switch code block
https://www.sololearn.com/learn/C/2924/