C++ standard says in section 4.12,
An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false any other value is converted to true.
Which means that the following code is valid,
if(5)
std::cout << "WOW!";
It is syntactically valid but semantically it doesn't make any sense. My question is why C++ is allowing such strange things? AFAIK, it is not making any advantage rather than making confusion.
I think it's historical, and a by product of how C used to evaluate bool like concepts...
C didn't use to have a boolean type, and in the 'down to the metal' paradigm of C, pointers and numeric types, etc. that were set to NULL were also implicitly false.
If you think of it as 'nothing/zero == false' and 'anything else == true' it actually does make sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With