albiero
albiero

Reputation: 91

C++ unable to use enum and switch together

From what I've seen, I should be able to run a switch on a enum, but mine is spitting back errors:

enum EMETH {TRAP=1, SIMP=2, MIDP=3, SINF=4};



switch(METH)
{
    case "TRAP":
        Meth=&Integrators::Trap;
        break;
    case "SIMP":
        Meth=&Integrators::Simp;
        break;
    case "MIDP":
        Meth=&Integrators::Midp;
        break;
    case "SINF":
        Meth=&Integrators::SInf;
        break;
}

The errors are

 error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]
       case "TRAP":
 error: ‘(int)((long int)"TRAP")’ is not a constant expression

for each case.

Upvotes: 1

Views: 342

Answers (1)

Gabriel
Gabriel

Reputation: 3584

By putting quotes around the names of the enum members, you've made them string constants. Thus the error that you're doing an invalid conversion. Switch statements operate on ordinals, which is what enum members are. So remove the ""s.

enum EMETH {TRAP=1, SIMP=2, MIDP=3, SINF=4};

switch(METH)
{
    case TRAP:
        Meth=&Integrators::Trap;
        break;
    case SIMP:
        Meth=&Integrators::Simp;
        break;
    case MIDP:
        Meth=&Integrators::Midp;
        break;
    case SINF:
        Meth=&Integrators::SInf;
        break;
}

Upvotes: 7

Related Questions