readability-implicit-bool-conversion

This check can be used to find implicit conversions between built-in types and booleans. Depending on use case, it may simply help with readability of the code, or in some cases, point to potential bugs which remain unnoticed due to implicit conversions.

The following is a real-world example of bug which was hiding behind implicit bool conversion:

class Foo {
  int m_foo;

public:
  void setFoo(bool foo) { m_foo = foo; } // warning: implicit conversion bool -> int
  int getFoo() { return m_foo; }
};

void use(Foo& foo) {
  bool value = foo.getFoo(); // warning: implicit conversion int -> bool
}

This code is the result of unsuccessful refactoring, where type of m_foo changed from bool to int. The programmer forgot to change all occurrences of bool, and the remaining code is no longer correct, yet it still compiles without any visible warnings.

In addition to issuing warnings, fix-it hints are provided to help solve the reported issues. This can be used for improving readability of code, for example:

void conversionsToBool() {
  float floating;
  bool boolean = floating;
  // ^ propose replacement: bool boolean = floating != 0.0f;

  int integer;
  if (integer) {}
  // ^ propose replacement: if (integer != 0) {}

  int* pointer;
  if (!pointer) {}
  // ^ propose replacement: if (pointer == nullptr) {}

  while (1) {}
  // ^ propose replacement: while (true) {}
}

void functionTakingInt(int param);

void conversionsFromBool() {
  bool boolean;
  functionTakingInt(boolean);
  // ^ propose replacement: functionTakingInt(static_cast<int>(boolean));

  functionTakingInt(true);
  // ^ propose replacement: functionTakingInt(1);
}

In general, the following conversion types are checked:

The rules for generating fix-it hints are:

Some additional accommodations are made for pre-C++11 dialects:

Occurrences of implicit conversions inside macros and template instantiations are deliberately ignored, as it is not clear how to deal with such cases.

Options

AllowIntegerConditions

When true, the check will allow conditional integer conversions. Default is false.

AllowPointerConditions

When true, the check will allow conditional pointer conversions. Default is false.