In order to understand why thy have to be intengers in the case statments. you need to understand the differance btween the switch and if statments. chained if statments are compairsons followed by conditional jumps.
So if you have
if ( x== 1 || y == 2 )
it compairs x to one, If x == one jumps to the code block for true.
if x != 1 it fall through to the next compairson of Y == 2
assuming we fell through we check if y==2
if y != TRUE we jump to the end of the code block for TRUE.
if it is TRUE it just falls through to the TRUE code block.
in the assembled code you end up with something like.
:x int; // a memory location set asside for the x varaiable
:y int; // x and y are both lables.
...
mov eax, &x // move x into the eax regester.
cmp eax,1 // UpDate the flags regesters as if we subtracted 1 form the eax regester.
jmpz &TrueBlock // jump to lable TrueBlock if the zero flag is set in the e-flags regester.(they where equal)
mov eax, &y // move y into the eax regester.
cmp eax, 2 // UpDate the flags regesters as if we subtracted 2 form the eax regester.
jmpnz &EndIf // jump to the lable EndIf if the zero flag is not set ( y!=2)
:TrueBlock // lable for where the true block begins.
// code to excute for the
// TRUE block goes here.
....
:EndIf // lable to mark the end of the If block.
so basickly if x ==1 it never checks to see what y is equal to. However if it is not Y will then be checked.
This is not how switch/case work however, switch/cases are not comparsions. they are calculations into a look up table. The look up table is nothing more then an array of memory locations to jump to. I do not have time at the moment to write it out in assemble but here is the jist of it.
switch(x)
{
case 1:
// code for case 1.
break;
case 2:
//code for case 2.
break;
}
now a compairson between x and 1 is neven done. instead it takes x and uses it as an index into a lookup table. the lookup table is an array of memory locations for where each code block starts. The size of a memory address in 32 bit programming is 4 bytes. So it takes the value of x multiplies it by four, then added the address, of the begining of the lookup table. it then jumps excution of the code to that location in memory. so there are no compairsions made, Just one calculation and then an indrect jump to the code block.
The breaks in the code would all be jumps to the lable at the end of the switch control structure. if the breaks are absent the code in following code blocks will also be excuted untill a break is hit.
Modifié par Lightfoot8, 19 août 2011 - 09:15 .