Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement with explicit static_cast to bool

Tags:

c++

Does if (static_cast<bool>(x)) make sense for some type of x?

Obviously if x is a bool, static_cast is not required.

If x is a raw pointer or std::unique_ptr or std::shared_ptr, then if (x) is alright (especially since std::unique_ptr and std::shared_ptr both have a bool operator). Maybe if (x != nullptr) might be better.

If x is an int, I guess if (x != 0) is preferred.

If x is a double, I guess if (x != 0.0) is preferred (although checking for exact floating point values has its own issues).

If x is some enum, if (x != E()) or if (x != E::whatever) probably is better than static_cast<bool>.

Are there any reasons to use if (static_cast<bool>(x)) for custom types (structs or classes) convertible to bool?

AFAIK the C++ Core Guidelines do not mention static_cast<bool> explicitly. I'm aware of following discussions: if (static_cast<bool>(x)) vs if (x) (which covers pointers only) and int to bool casting

like image 206
Jens Avatar asked Jan 24 '26 00:01

Jens


1 Answers

Does if (static_cast<bool>(x)) make sense for some type of x?

Yes for enum class:

enum class E {
    A = 1
};

E e = E::A;
if (e) {} // KO
if (static_cast<bool>(e)) {} // OK

For regular struct/classes, if (static_cast<bool>(x)) is equivalent to if (x), even for types with explicit operator bool, so you can use the later.

like image 138
Jarod42 Avatar answered Jan 25 '26 13:01

Jarod42



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!