Amxx
Amxx

Reputation: 3070

Why is !0 equal to 1 and not -1?

The following code

printf("!%d = %d\n", 0, !0);
printf("!%d = %d\n", 1, !1);
printf("!%d = %d\n", -1, !-1);

gives

!0 = 1
!1 = 0
!-1 = 0

Now, considering that 0 = 0x00000000, shouldn't !0 = 0xFFFFFFFF = -1 (for signed representation)? This messes up using int / long in a bitfield and inverting everything at once.

What is the reason behind this? Is it only to avoid !1 to be considered as the boolean true?

Upvotes: 2

Views: 7835

Answers (1)

juhist
juhist

Reputation: 4314

The reason is that in standard C, it has been specified that all operators returning a boolean return either 1 or 0. !0 calculates the logical not of 0, i.e. 1. The logical not of 1 would be then 0.

What you want to use is the bitwise NOT operator, i.e. ~0 which should be 0xFFFFFFFF == -1.

Upvotes: 20

Related Questions