zzzbbx
zzzbbx

Reputation: 10131

c++ switch case

whenever I try to use switch with

case myvar:

where myvar is a char I get an error. Is it possible to make it work? Thanks

Upvotes: -1

Views: 498

Answers (3)

Mahesh
Mahesh

Reputation: 34625

It seems you want your switch cases to work based on char. As others said, your switch cases should be integral compile-time constants. And the below example works because, the corresponding ASCII values are retrieved for each case of char.

#include <iostream>
int main( void )
{
    char myvar = 'a' ;
    switch( myvar )
    {
        case 'a':
            std::cout << "\n This Works !" << std::endl ;
            break ;
        default:
            break ;
    }

    return 0 ;
}

Hope this helps !

Upvotes: 1

John Dibling
John Dibling

Reputation: 101456

The expressions used in cases must be constant integral expressions that can be evaluated at compile time. So no. Unless myvar is a static const int of some sort, you can't make this work using case.

But what you can do is just use chained if statements.

Upvotes: 9

Will Robinson
Will Robinson

Reputation: 2289

In general, no. Cases must be compile-time constants.

Upvotes: 3

Related Questions