Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

switch statement - Portable way to do case a ... z in C

I'm using the following GCC extension to simplifying a big switch statement:

case 'a' ... 'z':
   ...

What's the proper/portable way to do this -- i.e., go through all the letters in a big switch -- or for this should a switch not be used.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Remember that default can be used for performing a task when none of the cases is true:

switch (x)
{
    case 1:
    case 2:
        printf("%d
", x);
        break;
    default:
        if (islower(x))
        {
            puts("alpha");
        }
        break;
}

Another way using the infamous goto:

if (islower(x))
    goto alpha;

switch (x)
{
    alpha:
        printf("alpha
");
        break;
    case 1:
    case 2:
        printf("%d
", x);
        break;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...