Search code examples
c++enumsbooleanstrong-typing

reducing errors using boolean arrays in C++


I'm working on a number of boolean variables that I am now converting into boolean arrays:

bool bool_var -> bool bool_var[SIZE]

This leads to error prone behavior, since if previously:

if (bool_var) { ... }

could return both "true" or "false", this same line of code always returns "true", since "bool_var" is now a pointer to the array. This is quite error-prone, especially if one is duplicating a large number of variables.

So here's the question: is there a less error-prone way of doing things?

The solutions I thought could work:

  1. Replacing the boolean type with a strongly typed enum (large overhead in C++03).
  2. Some compiler directive to trigger a warning (I couldn't find one..).

Any ideas?


Solution

  • Since you use arrays of a fixed size, you should use std::array, or boost::array if you don't have C++11-support in your compiler. Alternatively you might also consider using std::bitset.