Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 367
Prasad S Deshpande Avatar asked Oct 02 '14 06:10

Prasad S Deshpande


2 Answers

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).

like image 83
Emilio Garavaglia Avatar answered Oct 19 '22 04:10

Emilio Garavaglia


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") );
like image 44
Jonathan Potter Avatar answered Oct 19 '22 06:10

Jonathan Potter