我知道,如果什么时候谈论像这样的事情
,通常情况下开关案例会比其他情况更快if (a==0) statement1;
else if (a==1) statement2;
else if (a==2) statement3;
else statement4;
在这种情况下,编译器应该更容易有效地执行
switch (a){
case 0:
statement1;
break;
case 1:
statement2;
break;
case 2:
statement3;
break;
default:
statement4;
}
但我不知道下一个代码有什么用处:
#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;
}
它比这个更快吗?
#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);
}
}