Can you do multiple values on a switch statement?

Mar 17, 2015 at 3:33am
In the following code im trying to make it to where the user can enter either 1 or 2 to get the same result. I was wondering why this isnt working considering you can use a if(x == 1 || 2) statement. Is there a different way to do this? Or can you only use 1 value for case. (case 1, case 2, case 3, ect)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 #include <iostream>
#include <string>

using namespace std;

int main()
{

int x;

cout << "Enter a number: ";
cin >> x;

switch (x)
{
case  1 || 2:
    cout << "You're not a wizard larry";
    break;
default:
    cout << "You're a wizard harry";
}
}

Last edited on Mar 17, 2015 at 3:33am
Mar 17, 2015 at 3:37am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>

using namespace std;

int main()
{

	int x;

	cout << "Enter a number: ";
	cin >> x;

	switch (x)
	{
		case 1:
		case 2:
			cout << "You're not a wizard larry";
			break;
		default:
			cout << "You're a wizard harry";
	}
}
Mar 17, 2015 at 3:40am
Thank you for helping. But what if I wanted to do lets say number 1 - 300. Would I have to write

case 1:
case 2:
skip a few
case 300:
cout << "Words";
break;

Mar 17, 2015 at 3:43am
If you have to do that, you are better off with if() statements. switch is not designed to be used that way, and there is no easy way to check a wide range like that.
Mar 17, 2015 at 3:53am
Mmmk, was just checking if those were valid in switch. Thank you.
Topic archived. No new replies allowed.