#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.
The idea of a
switch
statement is that the compiler can produce code that only inspects theswitch
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 suchcase
expressions to see if there is one that matches. So instead of evaluating one expression, it would have to evaluaten
expressions, wheren
is the number ofcase
labels for thatswitch
.The whole idea of the
switch
is to do it the other way round than you did. Put the varying expressiona
in theswitch
itself, and put constants such as your'c'
in the case.The C99 standard says this (and the C89 standard was very similar):
That's the language requirement: case labels shall be integer constant expressions, and all the cases in a single switch shall be unique. That is the way C was designed. It is very unlikely to change now (even though the change would not break any currently valid code, or even change its meaning).
Think about, what if you had the following:
What would it return?
The case labels need to be constant so that the compiler can prove that there are no ambiguities.