0

I'm trying to use cons int labels in switch statement but I keep getting errors that the case label does not reduce to an integer constant even thought they are const int variables. I defined the const int variables like this:

const int ADD = 6;
const int AND = 7;
const int OR = 8;
const int XOR = 9;
const int SLT = 10;
const int SLL = 11;
const int SRA = 12;
const int SUB = 13;

and I use them in my switch statement like this:

switch(alu_op_code)
    {
        case ADD:
            C = A + B;
            break;
        case AND:
            C = A & B;
            break;
        case OR:
            C = A | B;
            break;
        case XOR:
            C = A ^ B;
            break;
        case SLT:
            C = A < B;
            break;
        case SLL:
            C = (unsigned int)A << B;
            break;
        case SRA:
            C = A >> B;
            break;
        default:
            C = 0;
            break;
    }

These are the errors in getting: enter image description here

How do I fix this?

1 Answers1

-1

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.

Hossein
  • 492
  • 2
  • 9