Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statements 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 won't compile for this error:

case label does not reduce to an integer constant

Why is this not allowed?

like image 487
Je Rog Avatar asked Aug 13 '11 14:08

Je Rog


3 Answers

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.

like image 167
Joshua Avatar answered Oct 13 '22 01:10

Joshua


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.

like image 22
Peter Alexander Avatar answered Oct 13 '22 02:10

Peter Alexander


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.

like image 28
Jens Gustedt Avatar answered Oct 13 '22 03:10

Jens Gustedt