Search code examples
c++implicit-conversion

Will implicit conversions lose information?


According to https://www.learncpp.com/cpp-tutorial/44-implicit-type-conversion-coercion/

"The important thing to remember about promotions is that they are always safe, and no data loss will result."

However https://www.geeksforgeeks.org/type-conversion-in-c/ states that:

"It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long long is implicitly converted to float)."

I understand that implicit conversions are safe, but I don't see how no data loss will result. Which is accurate?


Solution

  • The first article talks about promotions, which is a specific type of implicit conversion. There are other types of conversions that are also implicit conversions but aren't promotions. A promotion can't lose information as you are always going to a wider type, i.e. a type where all the values representable by the type being promoted are representable by the type being promoted to (int -> long long, for example).

    Other implicit conversions include: going from signed to unsigned, narrowing conversions, floating point to integer conversions. These conversion may lose information, unlike promotions.