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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With