-
switch case
I tryed to figure out this bug for 2 hours, couldn't get it. I'm just trying to make sure I know how to do this (its not homework) and this is the only thing I could think of making. I am using DJGPP and every time I try to run it, all of the case lines get an error. Whats wronge? It worked in BASIC!!!
Code:
switch ( age ) {
case >= 0 && < 5:
cout <<"You are a toddler!\n";
break;
case >=5 && < 13:
cout <<"You are a kid!\n";
break;
case >= 13 && < 19:
cout <<"You are a teenager!\n";
break;
case >= 20 && < 30:
cout <<"You are a young adult!\n";
break;
case >= 30 && < 55:
cout <<"You are an adult!\n";
break;
case >= 55:
cout <<"You are a valued old dude!\n";
break;
}//end switch
Please help! Thanks!!!
-
You cannot make case statements like that with ranges. You must explicitly make a case statement for each possible value (not recommended), use if/else statements, or use an advanced solution like a map.
-
Thanks! but wow... thats pretty stupid. at least i know i know how to use switch case...
-
Additionally, each time you use a comparison operator, it must have an operand on each side (there is no such thing as implicit operands). That is, the following: 'if (x < 2 && > 1)' meaning, 'if x less than 2 and x is greater than 1' will not fly.
There is no real reason to do this in this case, but you could also put people into age 'bins', and use a switch:
Code:
enum age_category { ac_toddler, ac_kid, ac_teenager, ac_adult, ac_older_than_dirt };
age_category cat;
if(age < 5)
cat = ac_toddler;
// etc...
else
cat = ac_older_than_dirt;
switch(cat)
{
case ac_toddler:
std::cout << "A toddler!" << std::endl;
break;
// etc...
}
The only reason to do this would be if you needed that information (which category a person is in) too often to make recomputing it tedious (... if the code would show up many places).