让我们一起来深入探讨 C/C++ 中位运算符与逻辑运算符的区别。位运算符(Bitwise AND)用符号 INLINECODEca738fd8 表示,而逻辑运算符用符号 INLINECODE407d759b 表示。以下是这两个运算符之间的一些主要区别。
a) 逻辑与运算符 && 期望它的操作数是布尔表达式(即 1 或 0),并且返回一个布尔值。
位与运算符 & 作用于整型(如 short, int, unsigned, char, bool, unsigned char, long)值,并返回整型值。
C++
#include
using namespace std;
int main()
{
int x = 3; //...0011
int y = 7; //...0111
// ‘&&‘ 的典型用法
if (y > 1 && y > x)
cout<<"y is greater than 1 AND x
";
// '&' 的典型用法
int z = x & y; // 0011
cout<<"z = "<< z;
return 0;
}
// this code is contributed by shivanisinghss2110
C
#include
int main()
{
int x = 3; //…0011
int y = 7; //…0111
// ‘&&‘ 的典型用法
if (y > 1 && y > x)
printf("y is greater than 1 AND x
");
// ‘&‘ 的典型用法
int z = x & y; // 0011
printf ("z = %d", z);
return 0;
}
Output
y is greater than 1 AND x
z = 3
Time Complexity: O(1)
Auxiliary Space: O(1)
b) 如果我们使用一个整型值作为本该用于布尔值的 && 操作数,在 C 语言中会遵循以下规则:
…..零被视为假,非零被视为真。
例如,在下面的程序中,x 和 y 被视为 1。
C++
#include
using namespace std;
// Example that uses non-boolean expression as
// operand for ‘&&‘
int main()
{
int x = 2, y = 5;
int z = x && y;
cout << " " << z;
return 0;
}
// this code is contributed by shivanisinghss2110
C
#include
// Example that uses non-boolean expression as
// operand for ‘&&‘
int main()
{
int x = 2, y = 5;
printf("%d", x&&y);
return 0;
}
Output
1
Time Complexity: O(1)
Auxiliary Space: O(1)
需要注意的是,如果对位运算符 & 使用非整型表达式,会导致编译错误。例如,下面的程序展示了编译错误。
C++
#include
using namespace std;
// Example that uses non-integral expression as
// operator for ‘&‘
int main()
{
float x = 2.0, y = 5.0;
cout <<" "<< x&y;
return 0;
}
// this code is contributed by shivanisinghss2110
C
#include
// Example that uses non-integral expression as
// operator for ‘&‘
int main()
{
float x = 2.0, y = 5.0;
printf("%d", x&y);
return 0;
}
Output:
error: invalid operands to binary & (have ‘float‘ and ‘float‘)
Time Complexity: O(1)
Auxiliary Space: O(1)
c) 如果第一个操作数已经为假,INLINECODE0720b107 运算符将不会计算第二个操作数。同样地,如果第一个操作数为真,INLINECODEb32326df 也不会计算第二个操作数。然而,位运算符 INLINECODEd1ef9333 和 INLINECODE880a9f2f 总是会计算它们的操作数。
C++
#include
using namespace std;
int main()
{
int x = 0;
// ‘Geeks in &&‘ is NOT
// printed because x is 0
printf("%d
", (x && printf("Geeks in && ")));
// ‘Geeks in &‘ is printed
printf("%d
", (x & printf("Geeks in & ")));
return 0;
}
//this code is contributed by aditya942003patil
C
#include
int main()
{
int x = 0;
// ‘Geeks in &&‘ is NOT
// printed because x is 0
printf("%d
", (x && printf("Geeks in && ")));
// ‘Geeks in &‘ is printed
printf("%d
", (x & printf("Geeks in & ")));
return 0;
}
Output
0
Geeks in & 0
Time Complexity: O(1)
Auxiliary Space: O(1)
同样的区别也存在于逻辑或运算符 INLINECODE25806497 和位或运算符 INLINECODEb9125cbf 之间。