#include <stdio.h>
int main(int argc, char *argv[]){
char a = 'c';
switch('c'){
case a:
printf("hi\n");
}
return 0;
}
The above won't compile for this error:
case label does not reduce to an integer constant
Why is this not allowed?
The compiler is explicitly allowed to use an efficient binary tree or a jump table to evaluate case statements.
For this reason, case statements are compile time constants.
Think about, what if you had the following:
int a = 1, b = 1, c = 1;
switch (a)
{
case b: return 1;
case c: return 2;
}
What would it return?
The case labels need to be constant so that the compiler can prove that there are no ambiguities.
The idea of a switch
statement is that the compiler can produce code that only inspects the switch
expression at run time and by that deduces the location to jump to.
If the case
label could be expressions that are not constant, it would have to evaluate all such case
expressions to see if there is one that matches. So instead of evaluating one expression, it would have to evaluate n
expressions, where n
is the number of case
labels for that switch
.
The whole idea of the switch
is to do it the other way round than you did. Put the varying expression a
in the switch
itself, and put constants such as your 'c'
in the case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With