C Boolean – What is !0 in C?

booleanc++

I know that in C, for if statements and comparisons FALSE = 0 and anything else equals true.

Hence,

int j = 40
int k = !j

k == 0 // this is true

My question handles the opposite. What does !0 become? 1?

int l = 0
int m = !l

m == ? // what is m?

Best Answer

Boolean/logical operators in C are required to yield either 0 or 1.

From section 6.5.3.3/5 of the ISO C99 standard:

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0.

In fact, !!x is a common idiom for forcing a value to be either 0 or 1 (I personally prefer x != 0, though).

Also see Q9.2 from the comp.lang.c FAQ.

Related Question