About switch statement

Please help me. I have code as following

Code:
#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
include <iostream>
using namespace std;
int main()
{
	int num = 1;
		switch (num)
		{
		case 1, 3, 5://causes error - (1)
			cout<<"Even";
			break;
		case 6..10://causes error - (2)
			cout<<"Unknown";
			break;
		default:
			cout<<"Ok";
		}
	return 0;
}

Why (1) and (2) cause errors. In switch of C++, doesn't support multiple const and interval constant ?
You get (syntax) errors because the syntax is incorrect.

The correct syntax is:
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>
using namespace std;
int main()
{
	int num = 1;
	switch (num)
	{
	case 1:
	case 3:
	case 5:
		cout<<"Even";
		break;
	case 6:
	case 7:
	case 8:
	case 9:
	case 10:
		cout<<"Unknown";
		break;
	default:
		cout<<"Ok";
	}
	return 0;
}
gcc supports ... syntax:

1
2
3
4
5
6
7
int x=7;
switch(x)
  {
      case 5 ... 10:
      cout <<"between 5 and 10";
      break;
  }

But you shouldn't use it.
Last edited on
@kbw: I know it. But it's long and isn't useful. I want to make it shorter.
@Null: I use gcc to compile it. But doesn't support both .. or ...
I want to make it shorter.

Then use ifs and else ifs

I use gcc to compile it. But doesn't support both .. or ...
case 5 ... 10: // notice the spaces between numbers and ...
You can also say:

1
2
3
4
5
switch(x)
{
case 1: case 3: case 5:
    // ...
}

But 1, 3 and 5 are odd numbers. And it's much easier to figure out whether a number is even or odd by using the modulo operator:

1
2
3
4
5
6
7
8
if(x % 2)
{
    // it's odd
}
else
{
    // it's even
}
Topic archived. No new replies allowed.