简体   繁体   English

在带有指针变量的表达式右侧使用逻辑非运算符(两次)

[英]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的类型是boolvariable = !!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.

相关问题 逻辑运算符的右手操作数 || 由于调用 function(MISRA-C 2012Rule 13.5)而具有持续的副作用 - The right hand operand of a logical operator || has persistent side effects because of calling function (MISRA- C 2012Rule 13.5) “ &&”或“ ||”的右操作数 是可能有副作用的表达 - Right hand operand of '&&' or '||' is an expression with possible side effects 将首先评估表达式的右侧 - will right hand side of an expression always evaluated first 包含赋值运算符右侧数据类型的方括号 - Brackets containing a datatype on right hand side of assignment operator 逻辑非运算符 - Logical not operator on pointer 这是对逻辑“和”运算符的正确使用吗? - Is this a proper use of the logical “and” operator? 对变量和指针使用相同的名称两次(c编程) - Use same name twice for a variable and for a pointer(c programming) C中表达式的指针和正确评价 - Pointer and right evaluation of an expression in C 如何从屏幕右侧而不是 C 中通常的左侧按 output 进行打印? - How to print by output from the right hand side of the screen instead of the usual left hand side in C? 两次对指针变量进行类型转换,为什么? - Typecasting a pointer variable twice, why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM