Print instructions in C: variable in case?

#include <stdio.h> int main(int argc, char *argv[]){ char a = 'c'; switch('c'){ case a: printf("hi\n"); } return 0; } 

The above will not compile for this error:

 case label does not reduce to an integer constant 

Why is this not allowed?

+7
source share
4 answers

The compiler is explicitly allowed to use an efficient binary tree or jump table to evaluate case statements.

For this reason, case arguments are compile-time constants.

+5
source

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 will he return?

Case labels must be constant so that the compiler can prove that there is no ambiguity.

+4
source

The idea behind the switch is that the compiler can create code that only validates the switch expression at runtime and thereby outputs the location for the jump.

If the case label could be an expression that is not a constant, it would have to evaluate all such case expressions to see if there is one. Therefore, instead of evaluating one expression, he would have to evaluate expressions n , where n is the number of case labels for this switch .

The whole idea of switch is to do it the other way around than you. Put the variable expression a in the switch itself and put in it constants like your 'c' .

+3
source

The C99 standard says (and the C89 standard was very similar):

Β§6.8.4.2 switch statement

Limitations

ΒΆ1 The control expression of the switch statement must be an integer type.

[...]

ΒΆ3 The label expression of each case must be an integer constant expression, and there must not be two case constant expressions in the same switch statement must have the same value after conversion. A switch statement can have at most one default label.

What is a language requirement: case labels must be integer constant expressions, and all cases in one switch must be unique. That is how C. was designed. Now it is unlikely to change (although the change will not violate the current existing code or even change its value).

+2
source

All Articles