In C, given "short x = 0xFFF0" what is the output of "x && (~x)". This question was proposed to me on a quiz and the answer for it was 0. Although when compiled 1(true) is returned. Why is that?
int main()
{
short x = 0xFFF0;
printf("%X\n", x && (~x));
return 0;
}
What I know is that "x = 0xFFF0" and "~x = 0x000F". when we do "logical and" its 1 && 1 which returns 1(true). However, the professor thinks otherwise by stating that the "bitwise and" should be done first 0xFFF0 & 0x000F = 0x0000 which is 0 (false). Is this a problem with an outdated compiler or something unexplainable?
Let's look at x && (~x)
part by part.
x
by itself is not zero and will therefore count as true
in boolean contexts as when using the logical &&
(AND).~x
by itself is not zero either, so true
.true && true
is true
:#include <stdbool.h>
#include <stdio.h>
int main() {
short x = 0xFFF0;
printf("%s\n", x != 0 ? "true" : "false"); // true
printf("%s\n", ~x != 0 ? "true" : "false"); // true
printf("%s\n", true && true ? "true" : "false"); // true
}