为什么C语言中有||
和|
这两个运算符?据我所知,|
运算符可以替换||
在条件表达式中的使用,因为当至少有一个操作数非零时它会返回true(非零)值。
我只是出于好奇而问。 我知道在逻辑表达式中应该使用||
。
例子
#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;
}
||
短路,|
不会。 - Federico klez Culloca||
时保证短路:这意味着如果第一个比较为真,它就知道不必检查第二个。很多代码都依赖于||
和&&
的这种短路操作。 - Steve Friedl3 | 4
应该是 7。 - jiwopene&/&&
。已经修改了,谢谢。 - Eugene Sh.