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; }
7 Respuestas
+ 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;
}
0
default is executed only when all the given cases tends to be false, isn't it ?
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
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
0
Ah, well then the answer is 32 due to the reasons I stated above.
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 😊😊
- 1
@ Elie
case 1 is not ran x is 2