Search code examples
c++type-conversioncompiler-warningssignedtruncation

Implicit conversion warning int to int-lookalike


My compiler warms me about a lot of implicit conversion:

Some I do understand, like

implicit conversion changes signedness: 'int' to 'std::vector::size_type' (aka 'unsigned long')` 

when I do myvector.resize(myInt) .

Other more obscure, like

implicit conversion loses integer precision: 'std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::size_type' (aka 'unsigned long') to 'int'

when I do myInt=myString.size(), or

implicit conversion changes signedness: 'int' to 'std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::size_type' (aka 'unsigned long')

when I call myString[myInt]

I all cases, I do understand why I get these message (int-uint, etc), however their use is non-ambiguous in the program. What do I risk if I do not hunt change the type of my variables to delete these warning? My previous compiler didn't warn me of anything, so when I changed my PC I suddenly had dozens of warning.


Solution

  • I all cases, I do understand why I get these message (int-uint, etc), however their use is non-ambiguous in the program. What do I risk if I do not hunt change the type of my variables to delete these warning?

    It's not about ambiguity. If you convert a signed value to an unsigned type, you may get bizarre results:

    long i = -2147483645;        // for example
    
    std::vector<int> vec{0, 1, 2, 3, 4};
    std::cout << vec[i] << "\n"; // undefined behavior, not always caught
    

    Here, assuming a 32-bit system, i gets converted to 2147483651 before it is passed to operator[], causing undefined behavior.

    If you are really sure the conversion is harmless, you can do a static_cast:

    static_cast<std::vector<int>::size_type>(i)
    

    My previous compiler didn't warn me of anything, so when I changed my PC I suddenly had dozens of warning.

    Always turn on warnings. At least do -Wall. When writing libraries, I tend to make sure my code compiles cleanly even with -Wextra. They can help you catch a lot of bugs.