Reputation: 153
I'm reading Computer Systems a programmers perspective, and I'm getting into logical operators, which are similar to bitwise operators, but with a few differences.
What I CANNOT figure out is that when you have a logical operand !0x00 returns 0x01 rather than 0x11?
! is NOT, right? So NOT 0(false) should be 1(true) and another NOT 0(false) should also be 1(true) as well, right?
I look at the bitwise operator example : ~00, naturally that would return 11, but C's logical operators seem to work with vast differences.
Why does this happen?
What I have tried already: Reading a little further to find the answer I seek, it doesn't seem to be here.
What I think the problem is: Might have something to do with how Hexadecimals work? But, Hexadecimals can still have 0x11. . . .
Upvotes: 0
Views: 1611
Reputation: 343
The expression !n
is equivalent to (n==0)
. It returns 1
if true, 0
if false.
Upvotes: 2
Reputation: 60097
Neither !0x00
nor ~0x00
will give you 0x11
.
!n
is the same as n==0
and evaluates to 1
or 0
.
~n
negates the bits of the binary representation, not the digits of the literal you chose to enter the number.
Upvotes: 0
Reputation: 214300
Because that's how the language is defined. !
is the logical NOT operator and boolean logic in C works on 1
and 0
, representing true
and false
.
C17 6.5.3.3:
The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int.
You can think of it as if returning bool
, though it actually returns int
for backwards-compatibility reasons. Unlike C++ where it does return bool
. The same goes for relational and equality operators.
Upvotes: 6