What is !0 in C?
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 tr开发者_StackOverflow社区ue
My question handles the opposite. What does !0 become? 1?
int l = 0
int m = !l
m == ? // what is m?
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.
§6.5.3.3/5: "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."
The other logical operators (e.g., &&
, ||
) always produce either 0 or 1 as well.
Generally, yes, it'll become 1. That said even if that is guaranteed behavior (which I'm not sure of) I'd consider code that relied on that to be pretty awful.
You can assume that it's a true value. I wouldn't assume anything more.
The Bang operator (!) is the logical not operator found commonly in C, C++ and C#, so
!0 == 1
!1 == 0
This is based on the language characteristic of what is interpreted to be either true or false... in more modern languages it would be like this
!false == true
!true == false
See DeMorgan Law concerning truth tables...
!x
will be expand to (x==0)
so:
- if x=0 ->
!x
take value from(0==0)
= TRUE (value 1) - if x!=0 ->
!x
take value from(x==0)
= FALSE (value 0)
精彩评论