Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ !! conversion to bool

In C++ there is a construction !! applicable to non bool values to convert it to bool. For instance:

int n = 12;

if ( !!n )
  std::<<cout << "n is true";
else
  std::<<cout << "n is false";

Is there any restrictions where it can be applied, or which types is applicable: POD, pointers, etc.?

like image 378
Denis Solovov Avatar asked Feb 13 '26 15:02

Denis Solovov


2 Answers

The restriction is that operator! must be defined for the type (and it must yield a type for which operator! is also defined)

like image 72
jalf Avatar answered Feb 15 '26 04:02

jalf


It works for any type that can be evaluated in a boolean context. So arithmetic types, pointer types (including pointer-to-(member)(function)), and anything with a conversion to one of those. Plus odds and ends like enum types, std::nullptr_t, and probably something else I've forgotten. 4/3 in C++11 defines what contextually converted to bool means, and that's what the built-in operator! does.

For all of these types, writing if(!!n) is redundant, you can write if(n) with the same meaning. !!n for such types means the same as bool(n) or static_cast<bool>(n);.

It also works for any type with an overloaded operator! that returns a type that can be converted to bool (or that returns a type with operator! overloaded to return bool).

If the leftmost operator! returns a type other than bool, then you might still be able to write if(!!n), but !! doesn't act as a conversion to bool. It acts as a conversion to whatever type is returned.

like image 39
Steve Jessop Avatar answered Feb 15 '26 06:02

Steve Jessop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!