Oracle® Solaris Studio 12.4: C User's Guide

Exit Print View

Updated: March 2015
 
 

2.7 Case Ranges in Switch Statements

In standard C, a case label in a switch statement can have only one associated value. Solaris Studio C allows 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 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.

The following programming example illustrates case ranges in switch statements:

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; }  

Error conditions in addition to existing requirements on case labels are as follows::

  • If the value of low is greater than the value of high, the compiler rejects the code with an error message. Because the behavior of other compilers is not consistent, an error condition is the only way to ensure that programs will not behave differently when compiled by other compilers.

  • If the value of a case label falls within a case range that has already been used in the switch statement, the compiler rejects the code with an error message.

  • If case ranges overlap, the compiler rejects the code with an error message.

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