【发布时间】:2020-04-07 03:19:38
【问题描述】:
为什么 C 有 || 和 | 运算符?据我所知,| 运算符可以在条件中替换||,因为当至少有一个操作数为非零时,它将返回真(非零)值。
我只是出于好奇而问。我知道我应该使用 || 来表示逻辑表达式。
示例
#include <stdio.h>
int main(void) {
int to_compare = 5;
/* Try with bitwise or */
if ((5 > to_compare) | (to_compare == 6)) {
printf("‘to_compare’ is less than or equal to 5 or equal to 6.\n");
}
/* Try with logical or */
if ((5 > to_compare) || (to_compare == 6)) {
printf("‘to_compare’ is less than or equal to 5 or equal to 6.\n");
}
return 0;
}
【问题讨论】:
-
||短路,|没有。 -
一个关键的区别是
||保证短路:这意味着如果第一个比较为真,它知道它不必检查第二个。很多代码依赖于||和&&的这种短路操作 -
@EugeneSh。我以为
3 | 4会是 7。 -
@jiwopene 哎呀。当然是指
&/&&。已编辑,谢谢 -
@jiwopene 我认为该问题的答案以及问题本身也为您的关注提供了很好的答案:stackoverflow.com/questions/29810766/…
标签: c if-statement bitwise-operators logical-operators