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?
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.
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.
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);
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.
That is the case range extension of the GNU C compiler, it is not standard C or C++.
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:
^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With