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;
}
The expression
a && b
is abool
type and is eithertrue
orfalse
: it istrue
if and only if botha
andb
are non-zero, andfalse
otherwise. As your question mentions complementing schemes (note that from C++20, anint
is always 2's complement), -0 and +0 are both zero for the purpose of&&
.When assigned to the
int
typec
, thatbool
type is converted implicitly to either 0 (iffalse
) or 1 (iftrue
).(In C the analysis is similar except that
a && b
is anint
type, and the implicit conversion therefore does not take place.)