Reputation: 21
I have come across an answer and I can't seem to figure out why it's right.
So there are two int variables x and y and they represent 0x66 and 0x39 respectively.
The question asked what is the result value based on the expression.
x && y is apparently 0x01 (1)
x || y is 1
!x || !y is 0
x && ~y is 1
From what I was thinking, I thought as long as an argument was not zero it was considered true. So as long as x and y were some non-zero value then && operator would produce a 1, and of course as long as one of them is true the || operator would produce a 1.
So why is the third question 0? Is the ! different from the bitwise ~ operator? So originally x is 0101 0101 in binary since it's non zero it is true in the logical sense, but the ! of it would be false or would it do the one's complement of the number so its 1010 1010?
Upvotes: 0
Views: 672
Reputation: 213286
From what I was thinking, I thought as long as an argument was not zero it was considered true. So as long as x and y were some non-zero value then && operator would produce a 1, and of course as long as one of them is true the || operator would produce a 1.
This is all correct.
So why is the third question 0? Is the ! different from the bitwise ~ operator?
Yes. It is logical NOT. Just like the other logical operators &&
and ||
, it only cares about if a variable has a non-zero value or not.
!0
will yield 1
.
!non_zero
will yield 0
.
Note that all logical operators in C yield type int
rather than bool
, as an ugly, backwards-compatibility remain from the time before C had a boolean type. In C++ and other C-like languages, logical operators always yield type bool
.
Similarly, true
and false
in C are actually just macros that expand to the integers 1
and 0
. In other languages they are keywords and boolean constants.
Upvotes: 0
Reputation: 114
~(0x01) will 0x10 and !(0x01) will 0x00
'~' is a bitwise operator. '!' is a logical operator.
Upvotes: 0
Reputation: 409136
A boolean result is always true or false, and in C true is represented by 1
and false by 0
.
The logical not operator !
gives a boolean result, i.e. 1
or 0
. So if an expression is "true" (i.e. non-zero) then applying !
on that expression will make it false, i.e. 0
.
In your example you have !x || !y
. First !x
is evaluated, and it evaluates to false, leading to !y
being evaluated, and it also evaluates to false, so the while expression becomes false, i.e. 0
.
Upvotes: 1
Reputation: 15954
Yes, !
is different from the bitwise not ~
. It's a logical not. It yields either 0 or 1.
Upvotes: 0