Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case expression not constant

Tags:

c++

I am getting a 'case expression not constant' error in a switch statement. However, the header provides a definition for the used constants, and the constructor provides initialisation for them in its initialization list.

Additionally, when I mouse over the "problem" statements it identifies them as constants.

const int ThisClass::EXAMPLE_CONSTANT

error expression must have a constant value

This seems a little counter-intuitive to me. I did some research and found a similar problem that someone else had. They were told that all constants must in fact be initialised in 'main' and that this was a limitation of the language. Is this really the case? It seems unlikely.

like image 259
Dollarslice Avatar asked Nov 08 '11 11:11

Dollarslice


2 Answers

The case statements require integral value which must be known at compile-time, which is what is meant by constant here. But the const members of a class are not really constant in that sense. They're are simply read-only.

Instead of fields, you can use enum :

class ThisClass {     public:          enum Constants         {             EXAMPLE_CONSTANT = 10,             ANOTHER_CONSTANT = 20         };     }; 

And then you can write,

switch(c) {       case ThisClass::EXAMPLE_CONSTANT:                    //code                    break;       case ThisClass::ANOTHER_CONSTANT:                    //code                    break; }; 
like image 188
Nawaz Avatar answered Sep 21 '22 15:09

Nawaz


You need a "real" compile time integer constant. const in C++ means read-only, and a const variable can be initialized just like int y = 0; const int x = y;, making x a read-only copy of the value y had at the time of initialization.

With a modern compiler, you can either use enums or constexprs to store (integral) members of compile-time-constness:

class Foo {
public:
    static constexpr int x = 0;
    enum { y = 1 };
};

int main () {
    switch (0) {
    case Foo::x: ;
    case Foo::y: ;
    }
}
like image 33
Sebastian Mach Avatar answered Sep 24 '22 15:09

Sebastian Mach