17

I was browsing some code in the linux kernel and I came across the statements like case '0' ... '9':

To try this out I created the test program below.

#include <iostream>

int main()
{
    const int k = 15;

    switch (k)
    {
    case 0 ... 10:
        std::cout << "k is less than 10" << std::endl;
        break;
    case 11 ... 100:
        std::cout << "k is between 11 and 100" << std::endl;
        break;
    default:    
        std::cout << "k greater than 100" << std::endl;
        break;
    }
}   

The program above does compile although I have never come across the elipses in case statement construct before. Is this standard C and C++ or is this a GNU specific extension to the language?

doron
  • 27,972
  • 12
  • 65
  • 103
  • 6
    Ah, the swan song of Visual Basic. – Hans Passant May 08 '11 at 01:22
  • [what does this syntax of switch case mean in C?](https://stackoverflow.com/q/17699746/995714) – phuclv Jan 22 '20 at 07:24
  • Does this answer your question? [Are triple dots inside a case (case '0' ... '9':) valid C language switch syntax?](https://stackoverflow.com/questions/7043788/are-triple-dots-inside-a-case-case-0-9-valid-c-language-switch-syntax) – phuclv Jan 22 '20 at 07:24

3 Answers3

29

That is the case range extension of the GNU C compiler, it is not standard C or C++.

wkl
  • 77,184
  • 16
  • 165
  • 176
7

That's an extension. Compiling your program with -pedantic gives:

example.cpp: In function ‘int main()’:
example.cpp:9: error: range expressions in switch statements are non-standard
example.cpp:12: error: range expressions in switch statements are non-standard

clang gives even better warnings:

example.cpp:9:12: warning: use of GNU case range extension [-Wgnu]
    case 0 ... 10:
           ^
example.cpp:12:13: warning: use of GNU case range extension [-Wgnu]
    case 11 ... 100:
            ^
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • Now, I wonder why that would be pedantic. I assume -Wall show the same? – sehe May 07 '11 at 23:32
  • @sehe, `-Wall` does not show those warnings/errors for me, using either clang or gcc. – Carl Norum May 07 '11 at 23:33
  • 1
    thx. That is kind of amazing, seeing how much emphasis is on standards compliance. I for one have never dreamed to even try using '...' in my switch statement :) – sehe May 07 '11 at 23:35
1

This is a GCC extension to C, mentioned in this answer to what is basically a duplicate question, and confirmed in the GCC documentation.

Community
  • 1
  • 1
Jon Purdy
  • 53,300
  • 8
  • 96
  • 166