Compiler error C4244: 'initializing' : conversion from '__int64' to 'int', possible loss of data

11,991

Solution 1

There are two things that can conflict differently in different environments:

The first is auto as a deduced type is a C++11 feature. May be the linux compiler does not have it as a default (just use -std=c++11, and if it does not have it, upgrade!)

The other is that the return type of std::count is size_t, not int, and size_t to int conversion may lose data depending on on how size_t is defined (there is at least a signed / unsigned mismatch and eventually a different in size of the two types, like 32 bit for int and 64 bit for size_t).

Solution 2

The reason you get this warning is that on a 64 bit build, the standard containers use 64 bit values for size types, and implicitly converting a 64 bit value (e.g. size_t) to a 32 bit value (e.g. int) can lose data.

The actual data type returned by the count function, which in this case would be std::vector<T>::difference_type, is probably the best type to use if your compiler doesn't support auto. Using size_t would probably work without warning as well, and is a lot shorter to type.

Alternatively, if you're not bothered by the risk of data loss (e.g. are never planning to have more than 2^32-1 objects in the container) you can simply cast the warning away:

int count = static_cast<int>( std::count(stdVector.begin(), stdVector.end(), "element") );
Share:
11,991

Related videos on Youtube

Prasad S Deshpande
Author by

Prasad S Deshpande

Software developer.

Updated on June 26, 2022

Comments

  • Prasad S Deshpande
    Prasad S Deshpande almost 2 years

    I am trying to use std::count over std::vector as following:

    int count = std::count( stdVector.begin(), stdVector.end(), "element" );
    

    On windows, it gives the following compiler error.

    error C4244: 'initializing' : conversion from '__int64' to 'int', possible loss of data

    If I change the code as following on Windows compiler does not appear.

    auto count = std::count( stdVector.begin(), stdVector.end(), "element" );
    

    However, now I face the following error on linux for the above change.

    error: ISO C++ forbids declaration of 'count' with no type

    How would I use std::count which will get build on both the platform without any error?

  • Exectron
    Exectron over 9 years
    Yuck for casting. Better not to even suggest it. Much better to use the correct variable type.