What does this mean?

I've been learning how to use C++ for a week now, but I can't seem to figure out, why something is that. The tutorials have knowledge testers, but I can't figure out why the last question is what it is. Here is the question:

What is the result of the following code?

int x=0;

switch(x)

{

case 1: printf( "One" );

case 0: printf( "Zero" );

case 2: printf( "Hello World" );

}


the answer is "ZeroHello World",

but why? I don't get it, can someone help me please?
case N: is just a label, if you don't put a break or a return, control flow will continue ignoring following labels.
The code above is the same as:
1
2
3
4
5
6
7
8
9
int x = 0;

if ( x == 0 ) goto case_0;
else if ( x == 1 ) goto case_1;
else if ( x == 2 ) goto case_2;

case_1: printf( "One" );
case_0: printf( "Zero" );
case_2: printf( "Hello World" );
I still don't understand why the answer is ZeroHello World
I wrote:
case N: is just a label, if you don't put a break or a return, control flow will continue ignoring following labels.
Well, many people believe that the switch statement resolves to something like this:
1
2
3
if(x==1) do_something();
else if(x==2) do_something_else();
else if(x==3) do_yet_another_thing()


It's actually more like, depending on the initial value, you jump to a certain position in the switch statement. Once you are inside the switch statement, no further checks will be performed. All code following the entry point will be executed until you either hit a break or the end of the switch block.
Topic archived. No new replies allowed.