12th Apr 2019, 2:56 PM
Krishna Kumar
Krishna Kumar - avatar
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
13th Apr 2019, 4:53 AM
Anna
Anna - avatar
+ 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;
12th Apr 2019, 3:14 PM
Javier Felipe Toribio
Javier Felipe Toribio - avatar
+ 5
You're right Anna. It starts in case 3
12th Apr 2019, 4:06 PM
Javier Felipe Toribio
Javier Felipe Toribio - avatar
+ 4
Because there is no break, so three code blocks get executed, including under case 3 case 5 and default.
12th Apr 2019, 3:03 PM
Gordon
Gordon - avatar
+ 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)
12th Apr 2019, 3:27 PM
Anna
Anna - avatar
+ 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~
13th Apr 2019, 3:35 AM
Gordon
Gordon - avatar
+ 2
Thanks Anna.
13th Apr 2019, 8:19 AM
Krishna Kumar
Krishna Kumar - avatar
+ 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)?
13th Apr 2019, 3:55 AM
Krishna Kumar
Krishna Kumar - avatar
+ 1
Because you need to use break; statement to get out of the switch code block https://www.sololearn.com/learn/C/2924/
13th Apr 2019, 4:10 AM
Gordon
Gordon - avatar