What is "..." in switch-case in C code

CGccGcc Extensions

C Problem Overview


Here is a piece of code in /usr/src/linux-3.10.10-1-ARCH/include/linux/printk.h:

static inline int printk_get_level(const char *buffer)
{
  if (buffer[0] == KERN_SOH_ASCII && buffer[1]) {
    switch (buffer[1]) {
    case '0' ... '7':
    case 'd':  /* KERN_DEFAULT */
      return buffer[1];
    }
  }
}

Is it a kind of operator? Why does "The C Programming Language" not mention it?

C Solutions


Solution 1 - C

This is a gcc http://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html#Case-Ranges">extension called case ranges, this is how it is explained in the document:

>You can specify a range of consecutive values in a single case label, like this: > case low ... high:

You can find a complete list of http://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html">gcc extensions here. It seems like http://clang.llvm.org/docs/UsersManual.html#gcc-extensions-not-implemented-yet">clang also supports this to try and stay compatible with gcc. Using the -pedantic flag in either gcc or clang will warn you that this is non-standard, for example:

warning: range expressions in switch statements are non-standard [-Wpedantic]

It is interesting to note that http://www.ibm.com/developerworks/library/l-gcc-hacks/">Linux kernel uses a lot of gcc extensions one of the extensions not covered in the article is statement expressions.

Solution 2 - C

It is gcc compiler extension allowing to combine several case statement in one line.

Solution 3 - C

Beware, it is not standard C and therefore not portable. It is a shorthand devised for case statements. It's well-defined since in C you can only switch on integral types.

In standard C, ... is only used in variable length argument lists.

Solution 4 - C

case '0'...'7': is case ranges Speciacation in gcc.

Range specification for case statement.

Write spaces around the ..., for otherwise it may be parsed wrong when you use it with integer values

case '0' or case '1' or case '3' and so on case '7':
or case 'b' :
just return buffer[1]; 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjasonzView Question on Stackoverflow
Solution 1 - CShafik YaghmourView Answer on Stackoverflow
Solution 2 - CVladimirView Answer on Stackoverflow
Solution 3 - CBathshebaView Answer on Stackoverflow
Solution 4 - CGangadharView Answer on Stackoverflow