Search code examples
c++boolean

Why does bool exist when we can use int?


In computer science, the Boolean (bool) datatype has only two possible values, 'true' or 'false'. And also, in computer science, 1 is true and 0 is false. So why does Boolean exists at all? Why can not we use an integer that can return only two possible values, such as 1 or 0?

For example:

bool mindExplosion = true; // True!
int mindExplosion = 1; // True!!
// Or we can '#define true 1' and it's the same right?

What am I missing?


Solution

  • Why does bool exist when we can use int?

    Well, you don't need something as large as an int to represent two states so it makes sense to allow for a smaller type to save space

    Why not we use an integer that can return only two possible values, Such as 1 or 0.

    That is exactly what bool is. It is an unsigned integer type that represents true (1) or false (0).


    Another nice thing about having a specific type for this is that it express intent without any need for documentation. If we had a function like (warning, very contrived example)

    void output(T const & val, bool log)
    

    It is easy to see that log is an option and if we pass false it wont log. If it were instead

    void output(T const & val, int log)
    

    Then we aren't sure what it does. Is it asking for a log level? A flag on whether to log or not? Something else?