Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using range in switch case with exclusions C++

Tags:

c++

gcc

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

like image 766
Murphstar Avatar asked May 13 '26 05:05

Murphstar


2 Answers

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.

like image 124
Evg Avatar answered May 14 '26 20:05

Evg


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...............................
like image 33
Stéphane Gourichon Avatar answered May 14 '26 18:05

Stéphane Gourichon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!