In standard C, a case label in a switch statement can have only one associated value. Sun Studio (in an upcoming Studio Express Release) will allow an extension found in some compilers known as case ranges.
A case range specifies a range of values to associate with an individual case label. The case range syntax is:
case low ... high :
A case range behaves exactly as if case labels had been specified for each value in the given
range from low to high inclusive. (If low and high are equal, the case range specifies only the
one value.) The lower and upper values must conform to the requirements of the C standard. 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.
Example:
enum kind { alpha, number, white, other };
enum kind char_class(char c)
{
enum kind result;
switch(c) {
case 'a' ... 'z':
case 'A' ... 'Z':
result = alpha;
break;
case '0' ... '9':
result = number;
break;
case ' ':
case '\n':
case '\t':
case '\r':
case '\v':
result = white;
break;
default:
result = other;
break;
}
return result;
}
Note: If an endpoint of a case range is a numeric literal, leave whitespace around the
ellipsis (...) to avoid one of the dots being treated as a decimal point.
Example:
case 0...4; // error
case 5 ... 9; // ok
16 Jun · Mon 2008
Case ranges in switch statements - a handy extension to C
Trackback URL: http://blogs.sun.com/dpagan/entry/case_ranges_in_switch_statements
Post a Comment:
You shouldn't put blog entry text in pre tags. It makes it unreadable in my browser because I have to scroll down to find the horizontal scroll bar, then scroll horizontally, then scroll up, then back, ...
Posted by Nico on June 16, 2008 at 01:55 PM PDT #