Avoid C++ implicit conversions from bool

To most C++ programmers — or at least those like me with a short memory — it may feel like bool has always been there. However it is still not present in its ancestor C (though C99 has _Bool), and it was only introduced in C++98. At that time, there was resistance to it, and examination of existing code (that was mostly using macros to simulate a boolean type) showed that preventing implicit conversion between boolean values and integer numbers would have broken a lot of things. So in C++, bool-to-int conversion is implicit, with false converting to 0 and true to 1.

I think that this implicit conversion from bool is generally not needed in “real-world” code, and that it is in fact a source of bugs.

For example, this tweet shows that because of this implicit conversion, a typo like in int x = 1 < y; (where < was meant to be the left-shift operator <<) didn’t raise any alarm.

In my coding experience, I cannot think of useful cases where I need to convert a bool to something else, apart from printf statements used during debugging — but for these, I have taken the habit of doing an explicit conversion anyway, e.g.: printf("b=%d", int(b));.

I can certainly imagine cases where a bool could be converted to 0 or 1, to be used in a mathematical expression, e.g.: a = useC * c, but I think this would be better expressed as a = useC ? c : 0.

Of course my experience is limited, and there may be genuine situations where this conversion could genuinely help — Please let me know. But I think that in these cases, making the conversion explicit should be trivial, and also useful by making it more obvious (a = int(useC) * c). Now, if such conversion is needed for a lot of your code, maybe it’s a sign that the bool type may not be the right choice.

Note: clang-tidy offers readability-implicit-bool-conversion, but by default it catches more than just conversions from bool to int .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s