1
int main() 
{
    char boolean[][6]={"TRUE","FALSE"};
    printf("%s",boolean[(unsigned int)-1 == ~0]);
}

After executing, I get it as FALSE. What is the reason?

1
  • You should ask whoever wrote this code why they would place "TRUE" at index 0 and "FALSE" at index 1. Since it makes as little sense as #define TRUE 0.
    – Lundin
    Commented Apr 23, 2015 at 10:51

2 Answers 2

11

Because

~0 == 0xffffffff  (the ~ operator inverts all bits)

and

(unsigned int)-1 == 0xffffffff

as

(0xffffffff == 0xffffffff) == 1

your expressions boils down to

boolean[1]

which results in

"FALSE"
2

This is a mental trick.

(unsigned int)-1 == ~0
0xffffffff == 0xffffffff
1

and boolean[1] points to FALSE, so the output is correct.

But in your mind, the condition expands to true so why is the output FALSE?

Answer: The ordering of elements in the boolean[] array is wrong or at least not what it should be to give the expected results.

It's along the lines of

#define TRUE 0
#define FALSE 1

and then wondering why the C compiler "ignores" the "new rules" for truth values and code suddenly becomes buggy and convoluted.

1
  • 2
    The only valid definition for FALSE is #define FALSE ('-'-'-'). TRUE can, of course, safely be defined #define TRUE ('+'+'+') which immdiately ends the bad habit of comparing a condition to TRUE. Commented Apr 23, 2015 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.