[英]Use of logical not operator (twice) on right hand side of expression with pointer variable
Why would anyone type variable = !!ptr
as an expression?为什么有人会键入
variable = !!ptr
作为表达式? Looks like a bug or unintentional defect to me.对我来说,这看起来像是一个错误或无意的缺陷。 The result should be just
ptr
, but one must wonder the original intent.结果应该只是
ptr
,但人们一定想知道最初的意图。 Thoughts?想法?
The !
!
operator results in a value of 0 if its operand is equal to 0, or 1 otherwise.如果操作数等于 0,则运算符的结果为 0,否则为 1。
If ptr
is 0 (or NULL if it's a pointer), then !ptr
will evaluate to 1, and !!ptr
will evaluate to 0. If ptr
is not 0 (or not NULL), then !ptr
will evaluate to 0 and !!ptr
will evaluate to 1.如果
ptr
为 0(如果它是指针,则为 NULL),则!ptr
将评估为 1,并且!!ptr
将评估为 0。如果ptr
不为 0(或不为 NULL),则!ptr
将评估为 0 和!!ptr
将评估为 1。
So the end result of !!ptr
is that the value of ptr
is normalized to a boolean value, ie 0 will remain 0 and non-zero will be converted to 1.所以
!!ptr
的最终结果是ptr
的值被归一化为布尔值,即 0 将保持 0,非零将转换为 1。
For all scalar types, !x
is equivalent to x == 0
and !!x
is equivalent to x != 0
.对于所有标量类型,
!x
等价于x == 0
并且!!x
等价于x != 0
。 !!x
is hence an idiom to normalize x
as a boolean. !!x
因此是将x
标准化为布尔值的习惯用法。
If the type of variable
is bool
, variable = !!ptr
is indeed equivalent to variable = ptr
and will generate the same code.如果
variable
的类型是bool
, variable = !!ptr
确实等价于variable = ptr
并且将生成相同的代码。
Which one is more readable is debatable: implicit conversion to bool
is somewhat confusing and error prone because variable = ptr
would mean something totally different if variable
has a different integer type, whereas !!ptr
is safe and explicit, once you master the idiom.哪一个更具可读性是有争议的:隐式转换为
bool
有点令人困惑且容易出错,因为如果variable
具有不同的整数类型, variable = ptr
将意味着完全不同的东西,而!!ptr
是安全且明确的,一旦你掌握了习语。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.