Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Elipses in case statements standard C/C++

Tags:

c++

c

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?

like image 320
doron Avatar asked May 07 '11 23:05

doron


People also ask

Are there case statements in C?

Microsoft C doesn't limit the number of case values in a switch statement. The number is limited only by the available memory. ANSI C requires at least 257 case labels be allowed in a switch statement.

Can we use range in switch case in C?

Using range in switch case in C/C++ You all are familiar with switch case in C/C++, but did you know you can use range of numbers instead of a single number or character in case statement.

What is operator ellipsis?

An ellipsis is used to represent a variable number of parameters to a function. For example: void format(const char* fmt, ...) The above function in C could then be called with different types and numbers of parameters such as: format("%d-%d-%d", 2010, 9, 25);

Can a switch statement have a range?

That is, they must be valid integer constant expressions (C standard 6.8. 4.2). Case ranges and case labels can be freely intermixed, and multiple case ranges can be specified within a switch statement.


2 Answers

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

like image 180
逆さま Avatar answered Sep 17 '22 13:09

逆さま


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:
            ^
like image 26
Carl Norum Avatar answered Sep 19 '22 13:09

Carl Norum