Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ warning flag to avoid bool to double conversion

I look for a warning compilation flag of g++ that will prevent silent conversion from bool to double.

This answer relates to a broader question of conversion of int to double. The question was dismissed there because it's considered a lossless conversion and perfectly legal. However, since bool has another semantic meaning than simple integer, I expect that an implicit conversion from bool to double will issue a warning.

I've tried:
-Wall -Wextra -pedantic -Wconversion on the following code without any success (no warning issued):

#include <iostream>

int foo(double var){
   return static_cast<int>(var);
}

int main(){
   std::cout << foo(5) << std::endl;
   std::cout << foo(5.1) << std::endl;
   std::cout << foo(false) << std::endl; // here I want the warning
   return 0;
}

I use g++ 4.9.2, but an answer suggesting using higher version is perfectly acceptable.
Thanks.

like image 979
mikeraf Avatar asked Aug 26 '19 07:08

mikeraf


2 Answers

This is an approach that has nothing to do with gcc, but instead relies on another tool: clang-tidy has a readability-implicit-bool-conversion check that will warn you in this case. You need a separate static analysis check (which might take long to run, depending on your code base), but it works:

clang-tidy --checks=readability-implicit-bool-conversion your-file.cpp

yields

[...] warning: implicit conversion bool -> 'double' [readability-implicit-bool-conversion]  

std::cout << foo(false) << std::endl; // here I want the warning
                 ^~~~~
                 0.0
like image 72
lubgr Avatar answered Nov 12 '22 02:11

lubgr


The real problem is the implicit conversion from bool to int (which is followed by a second conversion to double).

Booleans were added lately to the C++ language and never really considered semantically different from a number (just as there is no true character type).

As there is no narrowing of the type, finding a warning condition is difficult.

If you have the option of turning the bools to a custom class (maybe just temporarily), you can overload the conversion operators.

like image 22
Yves Daoust Avatar answered Nov 12 '22 02:11

Yves Daoust