Are there any possible changes in the optimization while using a different syntax for the switch statement?

advertisements

Which is better performance in following two code snippets? and why?

Snippet 1:

 switch(a)
 {
      case 1 ... 5:
                   printf("%d\n",a);
                   break;
     case 6 ... 10:
                  printf("%d\n",a);
                  break;
    default:
            printf("%d\n",a);
 }

Snippet 2:

switch(a)
{
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
          printf("%d\n",a);
          break;
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
           printf("%d\n",a);
           break;
   default:
           printf("%d\n",a);
}


Both the snippets are same, they are not different. You're just using a different syntax for writing the code, that's all.

As already mentioned in comments, the first approach makes use of gcc extension for case-range. It allows you to write shorter code at the cost of portability, so choose wisely.

Any (half-decent) compiler, while generating the assembly, will generate the same code, so performance-wise there should be no difference.