Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C++ allows arithmetic or enumeration values to be implicitly converted to boolean?

Tags:

c++

boolean

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.

like image 292
Navaneeth K N Avatar asked Mar 21 '26 18:03

Navaneeth K N


1 Answers

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.

like image 193
John Weldon Avatar answered Mar 24 '26 08:03

John Weldon