Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

!0 guaranteed to be 1 in C89?

I've searched the standard but didn't notice the mentioned part.

Is it just "anything but 0" and 1 or it is compiler-dependent?

like image 616
susdu Avatar asked Feb 16 '16 18:02

susdu


People also ask

What does 0 evaluate to in C?

Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true. To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.

What is not of 0?

Because 0 is a whole number. The smallest natural number is 1, not 0 because natural numbers start from 1 and the whole numbers start from 0.


2 Answers

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. The result has type int.

Appears in C89/C90, C99, and C11.

like image 102
hobbs Avatar answered Oct 26 '22 14:10

hobbs


As hobbs said in his answer, section 6.5.3.3.5 of the C standard states that !0 evaluates to 1.

Additionally, this behavior can be used to normalize an integer to a boolean value (i.e. either 0 or 1) with the expression !!x.

  • When x = 0, !!x = !!0 = !1 = 0.
  • When x != 0, !x = 0, so !!x = !0 = 1.
like image 26
dbush Avatar answered Oct 26 '22 15:10

dbush