Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement of ranges

Is there a way to write a switch statement in c++ where you deal with ranges. case 0-10 do a, case 20-40 do b, case 40-80 do c, etc. I can write it out using a bunch of if else if statements but wondering if there is a more efficient way.

like image 508
Aaron Avatar asked Nov 24 '25 00:11

Aaron


1 Answers

Actually, you can do this through preprocessor abuse in C (although perhaps not in C++, due to some errors with P99 in C++, which I am confident could be overcome with enough perseverance).

See the following example, using P99:

#include "p99.h"

#define P99_SWITCH_RANGE(from, to) P99_FOR(from, P99_MINUS(to, from), P99_SWITCH_RANGE_GLUE_HELPER, P99_SWITCH_RANGE_CASE_LABEL_MAKER_HELPER)
#define P99_SWITCH_RANGE_GLUE_HELPER(from, i, past, cur) past: cur
#define P99_SWITCH_RANGE_CASE_LABEL_MAKER_HELPER(from, x, i) case P99_ADD(from, i)

int main(int argc, const char *argv[]) {
    int x;
    scanf("%i", &x);

    switch (x) {
        P99_SWITCH_RANGE(20, 30):
        {
            puts("between 20 and 30");
        }
        default: {
            puts("not between 20 and 30");
        }
    }
}

Note that this example is left inclusive, right exclusive. I'm confident you could modify the macros to make it any way you'd like, so this is a decent starting point at the very least.

like image 91
Richard J. Ross III Avatar answered Nov 26 '25 17:11

Richard J. Ross III