C/C++ 中的 "!<number> 是什么意思

What does "!<number> in C/C++ means

c中的!<number>是什么意思。例如 !-2!3?

cout << !-2;

Output:
0

cout << !3;

Output:
0

它被称为"logical not"。如果操作数为非零,则表达式的计算结果为 false;如果操作数为零,则表达式的计算结果为 true。将逻辑非应用于负零也 returns 正确。

一元运算符 ! 是逻辑否定(即 NOT)运算符。当操作数为真时,结果为假,当操作数为假时,结果为真。整数操作数隐式转换为布尔值。零为假,所有其他数字为真。

! 是逻辑否定运算符。来自 C 标准(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 expression !E is equivalent to (0==E).

来自 C++ 标准(8.3.1 一元运算符)

9 The operand of the logical negation operator ! is contextually converted to bool (Clause 7); its value is true if the converted operand is false and false otherwise. The type of the result is bool.

因此,例如,这个表达式

cout << !-2;

根据 C 引用等同于

cout << ( 0 == -2 );

在 C 中,运算符的结果具有类型 int,而在 C++ 中,运算符的结果具有类型 bool

请注意,在 C++ 中,您可以使用替代标记 not。例如上面的语句可以改写成

cout << not -2;

在 C 中,您可以包含 header <iso646.h> 并使用宏 not 作为运算符 ! 的替代记录。

还有一招。例如,如果你想从一个 C 函数到 return 一个整数表达式,初步将它准确地转换为 1 或 0 你可以这样写

return !!expression;

也就是说,如果 expression 不等于 0,则第一次应用运算符 ! 将表达式转换为 0,第二次应用运算符 ! 将结果表达式转换为 1

和写的一样

return expression == 0 ? 0 : 1;

但更紧凑。