Please explain the output. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Please explain the output.

#include <iostream> using namespace std; int main() { int x=2; switch (x){ case 1:{x*=x;} case 2:{x*=x;} case 4:{x*=x;} default :{x*=2;} } cout<<x; return 0; }

26th Jun 2017, 6:19 PM
Sanjeev Kumar
Sanjeev Kumar - avatar
7 Answers
+ 1
#include <iostream> using namespace std; int main() { int x=2;: //x=2 switch (x){//True all cases will be excuted case 1:{x*=x;} //2*2=4 case 2:{x*=x;} //4*2=8 case 4:{x*=x;} //8*2=16 default :{x*=2;} //16*2=32 } cout<<x; //32 return 0; }
26th Jun 2017, 6:26 PM
Elie Douaihy
Elie Douaihy - avatar
0
default is executed only when all the given cases tends to be false, isn't it ?
26th Jun 2017, 6:29 PM
Sanjeev Kumar
Sanjeev Kumar - avatar
0
Your break statements are missing. So all cases after a matching case will run (fall through). If there was no match then just the default would run. x is 2 case 2, case 4, and default are all ran case 2: x*=x 2 * 2 = 4 x is now 4 case 4: x*=x 4 * 4 = 16 x is now 16 default: x*=2 16 * 2 = 32 x is now 32 32 is output
26th Jun 2017, 6:31 PM
ChaoticDawg
ChaoticDawg - avatar
0
@chaoticdawg the question which I got didn't contain any break statement. this question was asked in a challenge round and didn't contain break statement
26th Jun 2017, 6:34 PM
Sanjeev Kumar
Sanjeev Kumar - avatar
0
Ah, well then the answer is 32 due to the reasons I stated above.
26th Jun 2017, 6:37 PM
ChaoticDawg
ChaoticDawg - avatar
0
yes now u can say the answer is 32. since there is no break statement, the code goes on working until it finds a final stop. I got it !!! thanks to both 😊😊
26th Jun 2017, 6:51 PM
Sanjeev Kumar
Sanjeev Kumar - avatar
- 1
@ Elie case 1 is not ran x is 2
26th Jun 2017, 6:31 PM
ChaoticDawg
ChaoticDawg - avatar