1. Description : codes to infer the difference betwwen operator ‘&’ and operator ‘&&’ in C
2. solutions :
#include<stdio.h>
int main(){
int a = 6;
int b = 3;
printf("a & b = %d\n", a & b);
printf("a && b =%d\n", a && b);
return 0;
}
results:
a & b = 2
a && b =1
3. Interpretation:
&&
operator is logical and
&
operator is bitwise and
The expression x&&y
will return 1
if both x
and y
is non-zero,and 0
otherwise. For example,(-1 && 8)
returns 1
,(1 && 8)
returns1
,(0,8)
returns 0
.
The expression x&y
will perform a bitwise operation on each individual bit in x
andy
.For example,(3,8)
will return 0
. Integer3
is 0011
in binary, integer 8
is 1000
,then (3 & 8 )
will return 0
. The return value should not be inerpreted as a boolean value.
&
has lower precedence than &&
The return value from x & y
should not be treated as a Boolean value at all. However, it can(depending on how the code is written) be treated as a Boolean array. If you have two integers, flag1
andflag2
then the result of flag1 & flag2
will denote which flags that are toggled in both flag1
and flag2
.
参考资料:
https://stackoverflow.com/questions/49617159/difference-between-and-in-c