Home > Software design >  Are there range operators in the C programming language?
Are there range operators in the C programming language?

Time:05-02

Are there range operators in C like there are in, say, Swift (closed range, open range)?
For example, in a switch statement, in Swift I would write this:

switch num {
    case 144...168:
    print("Something between 144 and 168")

    case 120..<144:
    print("Something between 120 and 143")
    
    default: break
}

If I try something similar in C, using printf instead of print of course, I cannot use the same range operators. Is there something I can use instead?
Thank you

CodePudding user response:

You can use a series of if statements.

When I do range matches, I create macros to simplify the code.

And, I've found that a do { } while (0); block can simplify things vs. a large if/else ladder.

Here is some code:

#define RNGE(_val,_lo,_hi) \
    (((_val) >= (_lo)) && ((_val) <= (_hi)))
#define RNGEM1(_val,_lo,_hi) \
    (((_val) >= (_lo)) && ((_val) < (_hi)))

do {
    if (RNGE(144,168)) {
        printf("Something between 144 and 168\n");
        break;
    }

    if (RNGEM1(120,144)) {
        printf("Something between 120 and 143\n")
        break;
    }

    // default ...
} while (0)

CodePudding user response:

Standard C (as of 2022...) does not provide such range operators.

But GCC provides case ranges as an extension:

6.30 Case Ranges

You can specify a range of consecutive values in a single case label, like this:

case low ... high:

This has the same effect as the proper number of individual case labels, one for each integer value from low to high, inclusive.

This feature is especially useful for ranges of ASCII character codes:

case 'A' ... 'Z':

Be careful: Write spaces around the ..., for otherwise it may be parsed wrong when you use it with integer values. For example, write this:

case 1 ... 5:

rather than this:

case 1...5:

Note the warning about spaces and integer values.

Also, this

case 120..<144:

in your hypothetical code would be written as

case 120 ... 143:

using the GCC extension.

  • Related