3

There is an extension in gcc which allows one to use "range" in a switch case statement.

case 'A' ... 'Z':

allows to make a case where a character is anywhere in the range A to Z.
Is it possible to make "exclusions" in a range statement like this? For example let's say I want my case to capture all characters A-Z except 'G' and 'L'.

I understand that a simple solution would be to handle the special characters within the body of the A-Z case but I would prefer if a solution described above existed

SergeyA
  • 61,605
  • 5
  • 78
  • 137
Murphstar
  • 99
  • 6

2 Answers2

2

As observed by commenters, this is not standard C++.

I would not use that in my code.

Nevertheless, with GCC's g++ it can work like this:

#include <iostream>

using namespace std;

int main()
{
    cout << "Case test" << endl;
    for (char c = '0'; c<'z'; c++)
    {
        switch (c)
        {
        case 'A'...('G'-1): case ('G'+1)...('L'-1): case ('L'+1)...'Z':
            cout << c;
            break;
        default:
            cout << ".";
            break;
        }
    }
}
g++ case.cpp -o case -W -Wall -Wextra -pedantic && ./case

case.cpp: In function ‘int main(int, char**)’:
case.cpp:15:9: warning: range expressions in switch statements are non-standard [-Wpedantic]
         case 'A'...('G'-1): case ('G'+1)...('L'-1): case ('L'+1)...'Z':
         ^~~~
case.cpp:15:29: warning: range expressions in switch statements are non-standard [-Wpedantic]
         case 'A'...('G'-1): case ('G'+1)...('L'-1): case ('L'+1)...'Z':
                             ^~~~
case.cpp:15:53: warning: range expressions in switch statements are non-standard [-Wpedantic]
         case 'A'...('G'-1): case ('G'+1)...('L'-1): case ('L'+1)...'Z':
                                                     ^~~~
Case test
.................ABCDEF.HIJK.MNOPQRSTUVWXYZ...............................
Stéphane Gourichon
  • 6,493
  • 4
  • 37
  • 48
  • 2
    Why do you have args to you main only to void them later? – SergeyA Jan 25 '19 at 21:11
  • @SergeyA it's an old habit, see [this answer](https://stackoverflow.com/questions/21045615/what-does-voidvar-actually-do). You're right that it's not longer necessary in modern [C](https://stackoverflow.com/questions/2108192/what-are-the-valid-signatures-for-cs-main-function) and [C++](https://en.cppreference.com/w/cpp/language/main_function), so I'm going to edit the answer. – Stéphane Gourichon Jan 26 '19 at 08:54
2
char c = /* init */;

switch(c)
{
case 'A' ... ('G'-1):
case ('G'+1) ... ('L'-1):
case ('L'+1) ... 'Z':
    /* some code */;
}

But I guess that

a simple solution ... to handle the special characters within the body of the A-Z case

would be much better than the code above.

Evg
  • 25,259
  • 5
  • 41
  • 83