validation参数为0或1

我有一个int类型的参数num ,用户可以给它一个两个值: 01
我可以用明显的方法检查它:

 if (num  1) print("The parameter value is incorrect.\n"); 

但我想知道是否有更好的(更快的?更少的代码?)这样做?

编辑
这是一些数据流代码,因此性能至关重要。 我正在寻找一种更快的方式来运行此检查。

谢谢

清除代码(天真)微优化

您实际上是在对实际编译器的行为做出错误的假设。 在这两种情况下,这是:

 if (num < 0 || num > 1) { ... 

 if (num != 0 && num != 1) { ... 

优化编译器会将其减少到最短的forms。 您可能会看到,两者都生成相同的程序集,可能看起来像(x86平台):

 cmp $0x1,%eax jbe 1e  # jump if below or equal 

这已经足够快了,因为所有主要架构上的cmp指令都有一个周期的延迟 。

最重要的是选择任何代码,使您的意图明确,未来的维护者,让编译器完成它的工作。 只需确保您使用适当的优化级别(例如-O2或更好)进行设置。


援助分支预测

但是,如果性能在这里非常重要(并且您将其描述为如此,不是吗?),那么您可以考虑另一种优化,即分支预测级别(假设您的CPU支持它)。 GCC具有__builtin_expect内在,允许提示编译器,在大多数情况下,分支将被采用。

您可以使用__builtin_expect为编译器提供分支预测信息。 一般来说,您应该更喜欢使用实际的配置文件反馈(-fprofile-arcs),因为程序员在预测程序实际执行情况方面是出了名的不好。 但是,有些应用程序很难收集这些数据。

例如,如果您有信心,该函数在大约99%的情况下需要01 ,那么您可以将其写为:

 #define unlikely(x) __builtin_expect((x), 0) if (unlikely(num != 0 && num != 1)) { ... 

我会继续清晰而不是更少的角色:

 if (num != 0 && num != 1){ print("The parameter value is incorrect.\n"); } 

当它是凌晨2点并且你正在调试程序时,你想要的最后一件事是过度考虑范围和按位操作。

 if (!!num == num) { /* value is either a zero or 1 */ } 

! 将其他值更改为0或1,因此如果您尝试传递5:

 if (1 == 5) // FALSE: 

你可以使用shift运算符

 if(num>>1) print("The parameter value is incorrect.\n"); 

由于唯一可以点亮的位是第一位,因此检查其余位是关闭的。

此外,因为它只有1 ,所以它的负面(在c语法中): ~1

所以:

 if (num & ~1) print("The parameter value is incorrect.\n"); 

同意if (num < 0 || num > 1) { ...是要走的路

以为我会添加一个代码类似高尔夫的答案

 if (num > 1u) { ... 

这将int num转换为unsigned然后再与1u进行比较。

这种方法的一个弱点是,如果num是一个比unsigned更宽的有符号类型。 在这种情况下,代码可以“让”我们变得更加默默无闻

 if (num > 1ull) { ... 

最后,使用(num < 0 || num > 1)

  1. 生成最快的代码

  2. 生成糟糕的代码,OP确实应该考虑一个比这种小代码优化更好的整体性能改进编译器。

有很多方法可以做到这一点。 我认为短路并不总是正确的。 认为有时您可能需要告知用户他的输入,而不仅仅是说“参数值不正确”。 我,我有自己的function,试试这个:

 #include int checkInput(int min, int max); int main(void){ int number = checkInput(0,1); printf("\nYour number is\t%d\n",number); return 0; } int checkInput(int min, int max){ int option,check; char c; do{ printf("Please type a number beetwen %d and %d:\t",min,max); if(scanf("%d%c",&option,&c) == 0 || c != '\n'){ while((check = getchar()) != EOF && check != '\n'); printf("\tI sayed a Number please\n\n"); }else if(option < min || option > max){ printf("\tThe number has to be beetwen %d and %d\n\n",min,max); }else{ break; } }while(1); return option; } 

输出:

 Please type a number beetwen 0 and 1: 0k I sayed a Number please 
 Please type a number beetwen 0 and 1: 1j I sayed a Number please Please type a number beetwen 0 and 1: 8 The number has to be beetwen 0 and 1 Please type a number beetwen 0 and 1: 1 Your number is 1