While implementing logical operations in the code, I discovered a phenomenon where it should not be entered in the if statement.
It turns out that this is the AND (&&)
operation of -1 and natural numbers.
I don't know why the value 1 is printed in the same code below. I ran direct calculations such as 1's complement and 2's complement, but no 1 came out.
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = -1;
int c = a && b;
printf("test = %d",c);
return 0;
}
CodePudding user response:
The expression a && b
is a bool
type and is either true
or false
: it is true
if and only if both a
and b
are non-zero, and false
otherwise. As your question mentions complementing schemes (note that from C 20, an int
is always 2's complement), -0 and 0 are both zero for the purpose of &&
.
When assigned to the int
type c
, that bool
type is converted implicitly to either 0 (if false
) or 1 (if true
).
(In C the analysis is similar except that a && b
is an int
type, and the implicit conversion therefore does not take place.)