Case ranges in switch statements - a handy extension to C

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
Comments:

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 06:55 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

dpagan

Search

Categories
Archives
« July 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today