About switch statement
Oct 21, 2010 at 3:55pm UTC
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 ?
Oct 21, 2010 at 4:03pm UTC
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;
}
Oct 21, 2010 at 4:08pm UTC
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 Oct 21, 2010 at 4:08pm UTC
Oct 21, 2010 at 4:13pm UTC
@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 ...
Oct 21, 2010 at 4:37pm UTC
I want to make it shorter.
Then use
if
s and
else if
s
I use gcc to compile it. But doesn't support both .. or ...
case 5 ... 10: // notice the spaces between numbers and ...
Oct 21, 2010 at 5:38pm UTC
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.