Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch case: error: case label does not reduce to an integer constant

Tags:

c

int value;  const int signalmin = some_function();  switch(value) {    case signalmin:    break; } 

I read the value of some_function and use that int value to do a switch case on. The C99 compiler gives back:

error: case label does not reduce to an integer constant

But I cannot use a #define because the int value is being read before the switch executes.

like image 771
Jim Clermonts Avatar asked Dec 28 '12 12:12

Jim Clermonts


People also ask

How do you fix a case label not within a switch statement?

How to fix? See the statement switch(choice); it is terminated by semicolon (;) – it must not be terminated. To fix this error, remove semicolon after this statement.

How is an integer constant used in the switch case structure?

The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion. There may be at most one default label in a switch statement.

Can label in switch statement must be constants only?

In C++ switch statement, the expression of each case label must be an integer constant expression.


2 Answers

switch labels must be constant expressions, they have to be evaluated at compile time. If you want to branch on run-time values, you must use an if.

A const-qualified variable is not a constant expression, it is merely a value you are not allowed to modify.

The form of integer constant expressions is detailed in 6.6 (6) [C99 and the n1570 draft of the C2011 standard]:

6 An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof or _Alignof operator.

The restriction that only sizeof expressions whose result is an integer constant are allowed rules out sizeof expressions whose operand is a variable length array.

like image 74
Daniel Fischer Avatar answered Sep 22 '22 05:09

Daniel Fischer


Let me chip in with an example. The following was tested on gcc version 4.6.3 with the flags -std=c99 -pedantic set:

#define SOME_HARDCODED_CONSTANT 0 //good int foo(int i, int b){     const int c=0; //bad     int a=0; //bad      switch(i){         case c:     //compile error         case a:     //compile error.         case (b+a): //compile error         case SOME_HARDCODED_CONSTANT: //all good         case 5: //all good     } } 

As others have noted, case arguments cannot be evaluated at runtime. Use an if-else block to do that.

like image 38
rath Avatar answered Sep 25 '22 05:09

rath