Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Should the expression x && (~x) return 1 or 0? And does it depend on the compiler?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading