Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I match a range instead of a single value in a C++ switch statement?

I am new into programming. Is it possible to use <, > in a switch case?

For instance,

 ...
 ...
 ...
 int i;
 cin>> i;
 ...
 ...
 switch(i){
 case 20<i<35
 ...
like image 240
modex Avatar asked Mar 15 '23 21:03

modex


1 Answers

C++ does not offer a switch syntax for matching ranges.

When ranges are relatively small, you could supply case labels, and rely on fall-through:

switch(i) {
    case 20:
    case 21:
    case 22:
    case 23:
    case 24:
    case 25: doSomething();
             break;
    case 26:
    case 27:
    case 28:
    case 29: doSomethingElse();
             break;
    ...
}

For medium-size ranges (1000 elements or so) you could use a vector of function objects to dispatch to a particular logic, but that requires a lot more work than writing a simple switch statement.

For large ranges your best bet is a chain of if-else statements.

like image 194
Sergey Kalinichenko Avatar answered Apr 28 '23 02:04

Sergey Kalinichenko