Why would anyone type variable = !!ptr
as an expression? Looks like a bug or unintentional defect to me. The result should be just ptr
, but one must wonder the original intent. Thoughts?
CodePudding user response:
The !
operator results in a value of 0 if its operand is equal to 0, or 1 otherwise.
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.
So the end result of !!ptr
is that the value of ptr
is normalized to a boolean value, i.e. 0 will remain 0 and non-zero will be converted to 1.
CodePudding user response:
For all scalar types, !x
is equivalent to x == 0
and !!x
is equivalent to x != 0
. !!x
is hence an idiom to normalize x
as a boolean.
If the type of variable
is bool
, variable = !!ptr
is indeed equivalent to variable = ptr
and will generate the same code.
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.