I know that usually switch case is faster than if else if when whe are talking about something like this
if (a==0) statement1;
else if (a==1) statement2;
else if (a==2) statement3;
else statement4;
In this case it should be easier for the compiler to perform efficiently
switch (a){
case 0:
statement1;
break;
case 1:
statement2;
break;
case 2:
statement3;
break;
default:
statement4;
}
But I do not know what hapens with the next code:
#include <stdio.h>
int main(){
int value;
puts("introduce a value (0-1000)");
scanf("%i" , &value);
if(value > 400) printf("%i is greater than 400", value);
else if (value >300) printf("%i is smaller than 401 and greater than 300", value);
else if (value >200) printf("%i is smaller than 301 and greater than 200", value);
else if (value > 100) printf("%i is smaller than 201 and greater than 100", value);
else printf("%i is smaller than 101", value);
return 0;
}
Is it faster than this one?
#include <stdio.h>
#include <limits.h>
int main(){
int value;
puts("introduce a value (0-1000)");
scanf("%i" , &value);
switch(value){
case 401 ... INT_MAX:
printf("%i is greater than 400", value);
break;
case 301 ... 400:
printf("%i is samller than 401 and greater than 300", value);
break;
case 201 ... 300:
printf("%i is samller than 301 and greater than 200", value);
break;
case 100 ... 200:
printf("%i is samller than 201 and greater than 100", value);
break;
default:
printf("%i is samller than 101", value);
}
}