【发布时间】:2015-06-30 21:21:54
【问题描述】:
网上有很多问题是指按位运算符和逻辑运算符之间的区别。希望我已经做了一个很好的搜索,它们都没有专门研究在条件语句中使用它们是否相同,也没有专门参考 C 语言。大多数人提到 C++ 和 C#,我不知道相同的答案是否也适用于 C 语言。
这是我编写的用于测试发生了什么的示例代码:
// Difference between logical && and bitwise & //
#include <stdio.h>
#define TRUE 123>45
#define FALSE 4>2342
void print_tt(int table[][4]);
int main(void) {
int and_tt[2][4]; // AND truth table
int or_tt[2][4]; // OR truth table
// Create truth table for logical and bitwise AND operator all in one 2d array
and_tt[0][0] = TRUE && TRUE ? 1 : 0;
and_tt[0][1] = TRUE && FALSE ? 1 : 0;
and_tt[0][2] = FALSE && TRUE ? 1 : 0;
and_tt[0][3] = FALSE && FALSE ? 1 : 0;
and_tt[1][0] = TRUE & TRUE ? 1 : 0;
and_tt[1][1] = TRUE & FALSE ? 1 : 0;
and_tt[1][2] = FALSE & TRUE ? 1 : 0;
and_tt[1][3] = FALSE & FALSE ? 1 : 0;
// Create truth table for logical and bitwise OR operator all in one 2d array
or_tt[0][0] = TRUE || TRUE ? 1 : 0;
or_tt[0][1] = TRUE || FALSE ? 1 : 0;
or_tt[0][2] = FALSE || TRUE ? 1 : 0;
or_tt[0][3] = FALSE || FALSE ? 1 : 0;
or_tt[1][0] = TRUE | TRUE ? 1 : 0;
or_tt[1][1] = TRUE | FALSE ? 1 : 0;
or_tt[1][2] = FALSE | TRUE ? 1 : 0;
or_tt[1][3] = FALSE | FALSE ? 1 : 0;
puts("_______AND_______");
puts("Logical Bitwise");
print_tt(and_tt);
puts("_______OR________");
puts("Logical Bitwise");
print_tt(or_tt);
}
// prints the truth table of the bitwise and logical operator given side by side
void print_tt(int table[][4]) {
int i;
for(i=0; i<4 ; ++i) {
printf("%-10s%s\n", table[0][i] ? "true" : "false",
table[1][i] ? "true" : "false");
}
}
程序的输出是:
_______AND_______
Logical Bitwise
true true
false false
false false
false false
_______OR________
Logical Bitwise
true true
true true
true true
false false
这证明了位运算符和逻辑运算符之间没有区别。修改TRUE和FALSE宏的定义,把剩下的比较运算符也包括进去,可以看出又没有区别了。
因此,如果存在差异,则可能与编译器解释语句的方式或代码的效率有关。
总之,在特定情况下,当我们在条件语句中的两个或多个比较操作的结果之间有一个按位或逻辑运算符时,我们应该使用两者中的哪一个,主要是为了提高效率?
【问题讨论】:
-
你的证明中有一个逻辑错误 :-) 你已经证明在一组案例中没有区别,并且错误地推断出所有案例都是正确的。
标签: c conditional-statements bitwise-operators logical-operators