msc
msc

Reputation: 34678

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

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

Upvotes: 1

Views: 71

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

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.

Upvotes: 6

Bathsheba
Bathsheba

Reputation: 234875

If in doubt profile it.

But note that the first snippet is not standard C (the range switch is a notable gcc compiler extension), and so is therefore not portable.

switch ((a - 1) / 5) would be an obvious alternative if you don't like duplicating case labels. But this could wind up being slower; again, profile it. Presumably you are aware that the printf is the performance bottleneck by a country mile?

Upvotes: 2

Related Questions