Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting the GNU case range extension to standard C

The GNU case range extension allows case ranges in switch statements:

switch (value) {
    case 1 ... 8:
        printf("Hello, 1 to 8\n");
        break;
    default:
        printf("Hello, default\n");
        break;
}

How would you convert this to standard C (c99, or c89)? Add the individual case statements?

Edit: How would you handle very large switch statements specifically?

like image 846
Ynv Avatar asked Mar 29 '12 09:03

Ynv


4 Answers

switch(value) 
{
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:
        printf("Hello, 1 to 8\n"); 
        break;     
    default:         
        printf("Hello, default\n");         
        break; 
} 

EDIT: To answer the comment.
If you have too many cases, then You might want to consider replacing the switch-case with if-else constructs. It can be much cleaner, concise & readable.

if (value >=1 && value <= 8) 
{    
    printf("Hello, 1 to 8\n"); 
} 
else 
{   
    printf("Hello, default\n"); 
}  
like image 164
Alok Save Avatar answered Nov 07 '22 06:11

Alok Save


I would use an if statement:

if (value >=1 && value <= 8) {
    printf("Hello, 1 to 8\n");
} else {
    printf("Hello, default\n");
} 

You can then add extra else if statements if more ranges are required,

like image 22
ouah Avatar answered Nov 07 '22 07:11

ouah


Alternatively, since the numbers are adjacent to each other, you can do a manual optimization of the switch-case.

typedef void(*func_t)(void);

#define CASES_N 9

void func0 (void)
{
  printf("Hello, 0\n");
}

void func1 (void)
{
  printf("Hello, 1 to 8\n");
}

static const func_t execute [CASES_N] =
{
  &func0,
  &func1,
  &func1,
  &func1,
  &func1,
  &func1,
  &func1,
  &func1,
  &func1
};

int main()
{
  if(what < CASES_N)
  {
    execute[what]();
  }
  else
  {
    printf("Hello, default\n");
  }
}

This code is basically the same as a compiler-optimized switch-statement.

like image 4
Lundin Avatar answered Nov 07 '22 08:11

Lundin


If long long range you could do, a bit dirty but,

switch(what) {
case 1:
    /* do 1 */
    break;
case 2:
    /* do 2 */
    break;
default:
    if (what > 31 && what < 127) {
         /* do 32 to 126 */
    }
}

The best would probably be to remove the switch for an if all together.

Be extremely strict with nesting. If you want the switch, for some reason, then better then the above would be:

if (value > 31 && value < 127) {
  /* Do something */
} else {
    switch (value) {
    case 1:
        ...
    }
}

Ach, sorry for edit again. This would be cleaner.

if (value > 31 && value < 127) {
  /* Do something */
} else if (value > 127 && value < 178) {

} else if ( ...

}

switch (value) {
case 1:
    ...
}
like image 2
Morpfh Avatar answered Nov 07 '22 08:11

Morpfh