+ 2

This code outputs '4' and I wanna know why [explain line by line if you can ; please ] thanks in advance .

int x=1; switch (x) { case1 : x++; case2 : x++; default : x++; } cout<< x ;

22nd Jan 2017, 3:43 PM
Amr Monsef
Amr Monsef - avatar
4 odpowiedzi
+ 9
There's no "break" keyword. So when the case matches (case 1:), it just proceeds to execute the code under. You will end up with 3 increments, which will give you 4 as a result.
22nd Jan 2017, 3:45 PM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 6
And for example if x=2, it will skip the first one, because it is lower than x.
22nd Jan 2017, 4:36 PM
Filip
Filip - avatar
+ 1
You r missing break; statement. It just increments 1 in each increment statements and outputs 4 . Technically it is not a switch case program....
28th Jan 2017, 9:36 AM
Zulkarnain Faizan
Zulkarnain Faizan - avatar
0
use break statement and compile it again
18th Feb 2017, 10:26 AM
Nomi Numan
Nomi Numan - avatar