about " switch statement "

  • Thread starter Thread starter iincity
  • Start date Start date
I

iincity

hi,all,
please see following:

int index = 0

switch(index){
case 0 - 10:
break;
default:
break;
}


this can compiler and run;
why?
 
Because it's the same as

int index = 0

switch(index){
case -10:
break;
default:
break;
}

So, the default case is executed as long as index is not -10.
 
iincity said:
hi,all,
please see following:

int index = 0

switch(index){
case 0 - 10:
break;
default:
break;
}


this can compiler and run;
why?

because 0 -10 is a compile time resolvable value(-10). The compiler allows
you to use expressions which can be resolved constantly at compiletime to
simplify code.

Most of the time this would be used for bit shifting (1<<5) for example or
multiplication (1024*1024*256). The compiler will then perform the
arithmetic and use the result as a constant.

Another thing this allows you to do is define constants like:

const int BytesPerK = 1024;
const int KPerMeg =1024;

and then use clearer switch cases like

switch (size)
{
case BytesPerK * KPerMeg * 256:
break;
}
 
Back
Top