!0保证在C89中为1?

时间:2022-06-30 07:20:34

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?

它只是“除了0之外的任何东西”和1还是依赖于编译器的?

2 个解决方案

#1


23  

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.

逻辑否定运算符的结果!如果其操作数的值比较不等于0则为0;如果其操作数的值比较等于0则为1.结果的类型为int。

Appears in C89/C90, C99, and C11.

出现在C89 / C90,C99和C11中。

#2


4  

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

正如霍布​​斯在他的回答中所说,C标准的第6.5.3.3.5节规定!0评估为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.

此外,此行为可用于将整数规范化为具有表达式!! x的布尔值(即0或1)。

  • When x = 0, !!x = !!0 = !1 = 0.
  • 当x = 0时,!! x = !! 0 =!1 = 0。

  • When x != 0, !x = 0, so !!x = !0 = 1.
  • 当x!= 0时,!x = 0,所以!! x =!0 = 1。

#1


23  

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.

逻辑否定运算符的结果!如果其操作数的值比较不等于0则为0;如果其操作数的值比较等于0则为1.结果的类型为int。

Appears in C89/C90, C99, and C11.

出现在C89 / C90,C99和C11中。

#2


4  

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

正如霍布​​斯在他的回答中所说,C标准的第6.5.3.3.5节规定!0评估为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.

此外,此行为可用于将整数规范化为具有表达式!! x的布尔值(即0或1)。

  • When x = 0, !!x = !!0 = !1 = 0.
  • 当x = 0时,!! x = !! 0 =!1 = 0。

  • When x != 0, !x = 0, so !!x = !0 = 1.
  • 当x!= 0时,!x = 0,所以!! x =!0 = 1。