New To Me

As I was preparing my material for an article, I accidentally discovered something that I’d never seen before; GCC now gives you the ability to specify a range in case statements.

switch (i) {
  case 0 ... 10:
     printf("zero through 10\n");
  break;

  default:
     printf("something else\n");
  break;
}

The syntax is a tad pedantic. You have to put white space before and after three dots. The white space is important, it gives a way for the compiler to tell the difference between specifying a range and a badly formed floating point value, like 3...14159.

This syntax is an extension that was added to GCC at some point for C99, but it also seems to work in Xcode and command line clang on a Mac. You might want to check your compiler to see if it works.

For Instance

I can imagine a few situations where this would be useful, like if you had some sort of enum representing ADC channels that should all be handled in the same way. Multiple case values should all do the same thing, like this::

switch ( variable) {
 case 0:
 case 1:
 case 2:
    statement;
    statement;
 break;

Using the new-to-me case ranges this could be written:

enum {ADC1, ADC2, ADC3};

switch ( variable) {
 case ADC1 ... ADC3:
    statement;
    statement;
 break;

Or if you are writing a command parser and are qualifying your input, it also works with character constants:

switch ( command) {
 case 'a' ... 'z':
    statement;

Should I or Shouldn’t I?

I can also imagine of a lot of situations where using case ranges might be avoided: when it makes the code less readable, when you really shouldn’t be using non-standard language extensions like when writing code for medical devices, and when you are writing code that may be used by a  compiler that doesn’t support this extension.

So, for hobby use, or using your judgement, case ranges could be very useful.


This post is part of a series. Please see the other posts here.


 MMMmm, licorice octopuses. My favorite seafood.

MMMmm, licorice octopuses. My favorite seafood.

 Music to work by: Chill Out electronic music stream from The Canadian Broadcasting Corporation.