
Simple switch statement question.
Quote:
> I would like to know if there is a way to use the switch statement to test
> for a range of values, for example:
> switch(SomeNumber)
> {
> case SomeNumber>10 && SomeNumber<20;
> cout << "You typed a number between 10 and 20" << endl;
> case SomeNumber>30 && SomeNumber<40;
> cout << "You typed a number between 30 and 40" << endl;
> default:
> cout << endl << "You entered something." << endl;
> }
> Thank you.
You could, if so inclined, define a function that would map the ranges you
are interested in to single numbers, e.g., Function(n) would return 1 if n
was between 10 and 20, return 2 if n was between 30 and 40 and so on. You
could then enter
switch(Function(SomeNumber))
{
case 1:
cout << "You typed a number between 10 and 20" << endl;
case 2:
cout << "You typed a number between 30 and 40" << endl;
etc. etc.
Quote:
}
With more effort, you could define a more general function that could be
used in a wide class of cases. Presumably
Visual Basic and the like do
something like this behind the scenes. Whether this would offer any
advantage over if-else tests is debatable (it probably would in some cases
but in others it would just slow things down).
If you want fixed width ranges, then just dividing will do the trick, e.g.,
if you enter
switch(SomeNumber/10)
{
// stuff
Quote:
}
then case 0 will apply to SomeNumber from 0 to 9, case 1 will apply to
SomeNumber from 10 to 19 and so on. More generally, if you enter
switch((SomeNumber - a)/b)
{
// stuff
Quote:
}
then each case (starting at case 0) will cover b different values of
SomeNumber, starting at SomeNumber = a. Thus case 0 covers SomeNumber values
from a to a+(b-1), case 1 covers the next b values of SomeNumber and so on.
--
Quixote
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)