Michael Celani
Michael Celani

Reputation: 181

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;
}

Upvotes: 4

Views: 210

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201399

Can switch statements use variables?

Yes. This is fine,

int i = 0;
switch (i) {
}

But, case statements cannot use variables (they must be constant).

case 0:
  // first
  break;
case 1:
  // second
  break;
default:
  // other

Upvotes: 3

Yu Hao
Yu Hao

Reputation: 122363

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.

Upvotes: 6

Related Questions