I've done some heavy refactoring of some C++ code, and discovered numerous bugs arising from implicit conversions that I'm not aware of.
struct A *a();
bool b() {
return a();
}
void c() {
int64_t const d(b());
}
b
, the return type of a
is silently cast to bool
.c
, the value returned from b
is silently promoted to int64_t
.How can I receive warnings or errors for the implicit conversion between primitive types?
-Wconversion
seems to only pick up several arbitrary conversions unrelated to the example above.BOOST_STRONG_TYPEDEF
is not an option (my types need to be PODs, as they're used in disk structures).In the C++ programming language, 3rd edition, appendix C.6, namely "Implicit Type Conversion", Bjarne Stroustrup classifies conversions as promotions and conversions: the first ones "preserve values" (that's your case 2), the second ones doesn't (case 1).
About conversions, he says that "The fundamental types can be converted into each other in a bewildering number of ways. In my opinion, too many conversions are allowed." and "A compiler can warn about many questionable conversions. Fortunately, many compilers actually do."
promotions on the other side are safe, and it seems like a compiler is not supposed to give a warning for them.
Compiler warnings are usually not mandatory. Usually in the C++ drafts and final ANSI documents it is reported that "implementers should issue a warning" where suggested: you can check it yourself for further information if needed.
EDITED: added C++11 note:
In The C++ programming language, 4th edition, the appendix of the 3rd edition has been reported and extended as section 10.5, "Implicit Type Conversion" again.
Being the previous considerations the same, C++11 more precisely define "narrowing conversions" and adds up the {}-initializer notation (6.3.5), with which truncations lead to a compilation error.