B
Brian J. Sayatovic
I've always been bothered by the restriction that case statements must
have constant integer values for their case expressions. That is, the
following is impossible:
int x = 10, y = 10;
switch(x) {
case y:
System.out.println("y=10");
break;
default:
System.out.println("y!=10");
break;
}
I could very easily turn that into cascading if statements:
int x = 10, y = 10;
if(x == y) {
System.out.println("y=10");
}
else {
System.out.println("y!=10");
}
So what is it about a switch statement that requires this restriction?
I would hope that there is some optimization or other advantage to
compensate for this disadvantage (really a pain when doing type-safe
enums, but hopefully JDK 1.5 will make that a moot point).
A VB programmer (yes, VB) once suggested that the compiler could
relate incoming values to instruction locations so that it wouldn't
have to test each value but merely jump directly to the location
needed. I tend to think that would be impossible since the incoming
value could take on any value.
Can someone enlighten me?
Regards,
Brian.
have constant integer values for their case expressions. That is, the
following is impossible:
int x = 10, y = 10;
switch(x) {
case y:
System.out.println("y=10");
break;
default:
System.out.println("y!=10");
break;
}
I could very easily turn that into cascading if statements:
int x = 10, y = 10;
if(x == y) {
System.out.println("y=10");
}
else {
System.out.println("y!=10");
}
So what is it about a switch statement that requires this restriction?
I would hope that there is some optimization or other advantage to
compensate for this disadvantage (really a pain when doing type-safe
enums, but hopefully JDK 1.5 will make that a moot point).
A VB programmer (yes, VB) once suggested that the compiler could
relate incoming values to instruction locations so that it wouldn't
have to test each value but merely jump directly to the location
needed. I tend to think that would be impossible since the incoming
value could take on any value.
Can someone enlighten me?
Regards,
Brian.