Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can switch statements use variables?

Below is code that declares two int variables and tries to use them in a switch statement. Is this a legal operation in C++? If not, why not?

int i = 0;
int x = 3;
switch (i)
{
    case x:
    // stuff
    break;

    case 0:
    // other stuff
    break;
}
like image 636
Michael Celani Avatar asked Jan 11 '23 02:01

Michael Celani


1 Answers

The case label must be an integral constant expression, so your example is invalid. But if x were changed to:

const int x = 3;

then it's valid.

like image 96
Yu Hao Avatar answered Jan 24 '23 04:01

Yu Hao