Extra Clang Tools 5 documentation

clang-tidy - readability-implicit-bool-cast

«  readability-identifier-naming   ::   Contents   ::   readability-inconsistent-declaration-parameter-name  »


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 cast:

class Foo {
  int m_foo;

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

void use(Foo& foo) {
  bool value = foo.getFoo(); // warning: implicit cast 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;
  // ^ propose replacement: functionTakingInt(static_cast<int>(boolean));

  // ^ propose replacement: functionTakingInt(1);

In general, the following cast types are checked:

The rules for generating fix-it hints are:

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

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



When non-zero, the check will allow conditional integer casts. Default is 0.


When non-zero, the check will allow conditional pointer casts. Default is 0.

«  readability-identifier-naming   ::   Contents   ::   readability-inconsistent-declaration-parameter-name  »