What is !0 in C?

后端 未结 5 1791
傲寒
傲寒 2020-12-06 09:59

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


        
相关标签:
5条回答
  • 2020-12-06 10:22

    §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.

    0 讨论(0)
  • 2020-12-06 10:24

    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.

    0 讨论(0)
  • 2020-12-06 10:24

    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.

    0 讨论(0)
  • 2020-12-06 10:36

    !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)
    0 讨论(0)
  • 2020-12-06 10:39

    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...

    0 讨论(0)
提交回复
热议问题