Share via


Visual C++, switch/case statement with a range of numbers.

Question

Sunday, November 28, 2010 2:42 AM

Hi, I came across a task, how to use switch / case with range of numbers?

for example:

int count;

switch(count)

{

   case 0 ... 999        : cout << "First Case"; break;

   case 1000 ... 1999 : cout << "Second Case"; break;

  .

  . 

}

 

I am not sure about syntax : if I want the case between numbers 0 and 999 inclusive how do I write?

Thanks in advance,

Gennady46

All replies (2)

Sunday, November 28, 2010 3:05 AM

There is no syntax for that kind of switch.  It is not supported by the language.  You can do it this way...

if (count >= 0 && count <= 999)

  ...

 


Sunday, November 28, 2010 10:14 AM

Hi, I came across a task, how to use switch / case with range of numbers?
 
for example:
 
int count;
switch(count)
{
   case 0 ... 999 : cout << "First Case"; break;
 
   case 1000 ... 1999 : cout << "Second Case"; break;
}

For this particular situation you can do
 
switch(count/1000)
{
   case 0: cout << "First Case"; break;
   case 1: cout << "Second Case"; break;
   // ....
}
 
David Wilkinson | Visual C++ MVP