I came across a weird observation recently when I came across below piece of program.
// Write C code here
bool abc = true;
bool cba = true;
bool bac = ~abc;
if(cba && bac)
{
printf("\nYES! %d", bac);
}
else
{
printf("\nNO! %d", bac);
}
return 0;
In the above program, I have observed that even though abc is true, if statement is getting executed and not else. Any explanation would be appreciated.
Note: But the same with " bool bac = !abc;", working as expected.
!and~.!logical not. Any non-zero value becomes zero and zero becomes1~bitwise not - negates all bits in the bitwise representation of the value. It can be applied to integer values only.~1becomes-2in two complement integersC standard 7.16.3:
6.2.5.2
The smallest type is
charand it has size (in bits) ofCHAR_BIT(minimum 8)Implicit conversions apply:
abcis converted tointand has the value1~operation is applied to theintvalue1trueas inClanguage any non-zero value is consideredtrue.bachas valuetrueIt will be an integer and it will have the value of
~1The only way to
~to reverse logical value is to use integer bitfield of size1https://godbolt.org/z/bjz6T4vTK