Introduction
This article deals with the use of bool in C++. Should we use it or not? That is the question we will try to answer here. However, this is more of an open discussion than a coding rule.
First of all, what is the bool type? A boolean variable is a variable that can be set to false
or true
.
Imagine you have a simple function to decide whether or not to buy an house, you may design it like this
bool shouldBuyHouse(bool hasSwimmingPool, bool hasEconomicLight);
Problems arrived!
Then, when you want to use it, you can do it like this:
if(shouldBuyHouse(false, true)){}
There is no problem here, however the reader may not understand at first glance if the false
means no pools, or if it means no energy saving lights.
So, you will try to change the function call like this:
bool economicLight = true;
bool hasSwimmingPool = false;
if(shouldBuyHouse(economicLight, hasSwimmingPool)) {
}
Now you are happy, the reader knows exactly what bool means. Are you sure? A very thorough reader may notice that there is a reversal of the parameters.
How to solve the problem?
There is different ways to solve this type of problem. The first is to use a strong_type
. There are many libraries that offer this kind of thing, however, a simple enum class
can do the trick.
Not only will the reader know which argument corresponds to which parameter, but also, in the case of a parameter inversion, the compiler will not let the error pass
Let’s rewrite the function declaration:
enum class HouseWithSwimmingPool {No, Yes};
enum class HouseWithLights {Economical, Incandescent};
bool shouldBuyHouse(HouseWithSwimmingPool, HouseWithLights);
if(shouldBuyHouse(HouseWithSwimmingPool::Yes, HouseWithLights::Economical)) {
}
Conclusion
I would encourage people not to use the bool
type for function parameters. What do you think? Do you use bool everywhere?
Thanks for reading !
Leave a Reply