位And运算符表示为“&”,逻辑运算符表示为“&&”。以下是这两个操作符之间的一些基本区别。
null
(a) 逻辑and运算符“&&”要求其操作数为布尔表达式(1或0),并返回布尔值。 按位and运算符“&”处理整数(short、int、unsigned、char、bool、unsigned char、long)值并返回整数值。
C++
#include<iostream> using namespace std; int main() { int x = 3; //...0011 int y = 7; //...0111 // A typical use of '&&' if (y > 1 && y > x) cout<< "y is greater than 1 AND x" ; // A typical use of '&' int z = x & y; // 0011 cout<< "z = " << z; return 0; } // this code is contributed by shivanisinghss2110 |
C
#include<stdio.h> int main() { int x = 3; //...0011 int y = 7; //...0111 // A typical use of '&&' if (y > 1 && y > x) printf ( "y is greater than 1 AND x" ); // A typical use of '&' int z = x & y; // 0011 printf ( "z = %d" , z); return 0; } |
输出
y is greater than 1 AND xz = 3
时间复杂性: O(1)
辅助空间:O(1)
b) 如果整型值用作“&&”的操作数,而“&&”应该用于布尔值,则C中使用以下规则。 …..零被视为假,非零被视为真。
例如,在以下程序中,x和y被视为1。
C++
#include<iostream> using namespace std; // Example that uses non-boolean expression as // operand for '&&' int main() { int x = 2, y = 5; cout<< " " << x&&y; return 0; } //this code is contributed by shivanisinghss2110 |
C
#include<stdio.h> // Example that uses non-boolean expression as // operand for '&&' int main() { int x = 2, y = 5; printf ( "%d" , x&&y); return 0; } |
输出
1
时间复杂度:O(1)
辅助空间:O(1)
将非整数表达式用作按位&的操作数是编译器错误。例如,下面的程序显示编译器错误。
C
#include<stdio.h> // Example that uses non-integral expression as // operator for '&' int main() { float x = 2.0, y = 5.0; printf ( "%d" , x&y); return 0; } |
输出:
error: invalid operands to binary & (have 'float' and 'float')
时间复杂度:O(1)
辅助空间:O(1)
c) 如果第一个操作数变为false,“&&”运算符不计算第二个操作数。类似地,当第一个操作数变为真时,“| |”不计算第二个操作数。按位“&”和“|”运算符始终计算其操作数。
C
#include<stdio.h> 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; } |
输出
0Geeks in & 0
时间复杂度:O(1)
辅助空间:O(1)
逻辑OR“| |”和按位OR“|”之间也有相同的区别。
本文由 乌杰瓦尔·贾因 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END