Switch statement without writing each case

Hi
I was just wondering if a switch statement can work without writing each case, for instance:

{ int age;
age=18;

while (age!=0)
{

cout<<"Enter age :"<<endl;
cin>>age;

switch (age)
{
case 0:
break;
case 1:
case 2:
case 3:
case 4:
cout<<"Tricycle"<<endl;
break;
case 5:
case 15:
cout<<"Bicycle"<<endl;
break;
case 16:
case 17:
cout<<"Motorcycle"<<endl;
break;
case 18:
case 100:
cout<<"Motorcar"<<endl;
break;
default:
cout<<"You probably shouldn't be driving"<<endl;
break;
}
}
cout<<"goodbye"<<endl<<endl;

It works only for values specifically entered as a case, for instance if you enter 5 or 15 , it says bicycle, but if you enter anything inbetween it goes to default.
Same with 18 and 100. It can't possibly be that you have to enter
case 19:
case 20:
case 21:
case 22:.......up to 100 to include all possible cases.
No, you can't. If you want to test age for a range of values, rather than for equality with specific values, you'll need to use if... else if... else.
I see. That's not cool.

Thanks for the quick reply.

I just thought about it ...A function can probably also be used, but I'll try to play around with that when I have more time. It might proof more complicated than just using the if-statements but I'll probably learn something...

Thanks again
1
2
3
4
5
6
7
8
9
10
11
unsigned int age ;
std::cin >> age ;

switch( (age<5) + (age<16) + (age<18) + (age<101) )
{
    case 4: std::cout << "Tricycle\n" ; break ; // 0-4
    case 3: std::cout << "Bicycle\n" ; break ; // 5-15
    case 2: std::cout << "Motorcycle\n" ; break ; // 16,17
    case 1: std::cout << "Motorcar\n" ; break ; // 18-100
    case 0: std::cout << "You probably shouldn't be driving\n" ; // 101-
}
This is really interesting!
Just trying to get my mind around it, how does the computer see it..
I tested it and it works perfectly, and I can use it in the future but I don't see why it works, considering how the computer sees it


Basically, (age<5) is like saying if ages < 5 then return the value 1, so keep that thought...

I enter age 24

so (age<5) would be false (0)
(age<16) would be false (0)
(age<18) would be false (0)
(age<101) would be true (1)

Add all those results together gives 1, which is 18 - 100.



Just so your clear, heres another..

I entered age 16.

(age<5) would be false (0)
(age<16) would be false (0)
(age<18) would be true (1)
(age<101) would be true (1)

returning 2, which is 16, 17

Just to extend on that ( I should have included it ), Boolean variables are either True or False, but in memory they are stored as 0 or 1 so when returning True from a function your actually returning the value 1
That makes perfectly sense, thank you. This is really helpful
Topic archived. No new replies allowed.