Ramakant
Ramakant

Reputation: 195

What is the output of thic C code? I need explaination

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?

Upvotes: 1

Views: 230

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328764

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.

Upvotes: 2

Jabberwocky
Jabberwocky

Reputation: 50831

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"

Upvotes: 11

Related Questions