关于!的用法温习
经典如是说
-
《C Programming Language》
-
By definition,the numeric value of a relational or logical expression is 1 if the relation is true,and 0 if the relation is false.The unary negation operator converts a non-zero operand into 0, and a zero operand in 1.
-
《ISO/IEC 9899:201x》
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).
简而言之
以!(cond)为例来说明:
- 取非运算,将cond和0比较;
- 结果为int类型的值;
例子
- if (flag) # flag为非0,则if条件判断为真
- if (!flag) # flag为0, 则if条件判断为真
关于!!(cond)
!!的含义
- !!(cond)等价于!(!cond),进行两次!运算,所以具体值如下面表格所示:
v/op | ! | !! |
---|---|---|
0 | 1 | 0 |
1(nonzero) | 0 | 1 |
也即:
!!(0) = 0
!!(1) = 1
!!(nonzero) = 1
!!的例子
#define IS_CAP_OF_XXX_FUNC (0x0000 0100)
INT32 cap = 0;
INT32 isSupportXXX = 0;
cap = get_chip_capability(); #读取芯片能力集
isSupportXXX = !!(cap & IS_CAP_OF_XXX); #为1表示支持XXX功能,0表示不支持XXX功能;
实际,!!只是缩短了代码行数,用if判断可达到同样的目的。
如本文对你有些许帮助,欢迎大佬打赏:
支付宝及微信打赏方式