Warnings or errors for C++ implicit conversion of primitives

Matt Joiner picture Matt Joiner · Dec 18, 2010 · Viewed 12.4k times · Source

I've done some heavy refactoring of some C++ code, and discovered numerous bugs arising from implicit conversions that I'm not aware of.

Example

struct A *a();

bool b() {
    return a();
}

void c() {
    int64_t const d(b());
}

Issues

  1. In b, the return type of a is silently cast to bool.
  2. In c, the value returned from b is silently promoted to int64_t.

Question

How can I receive warnings or errors for the implicit conversion between primitive types?

Note

  1. The use of -Wconversion seems to only pick up several arbitrary conversions unrelated to the example above.
  2. BOOST_STRONG_TYPEDEF is not an option (my types need to be PODs, as they're used in disk structures).
  3. C is also of interest, however this problem pertains to a C++ code base.

Answer

Sigi picture Sigi · Jan 29, 2014

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.