Reputation: 129
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
Upvotes: 3
Views: 1424
Reputation: 6981
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...............................
Upvotes: 2
Reputation: 26322
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.
Upvotes: 2