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?
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"
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.
#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
#define TRUE 0
.