c++vectorvisual-c++x86unsigned-long-long-int

X86 architecture - Set Vector size with unsigned long long


When I am trying to set vector size with unsigned long long in x86 architecture, I am seeing below error:

unsigned long long sz;
vec.resize(sz);

error C4244: 'argument': conversion from 'unsigned __int64' to 'const unsigned int', possible loss of data

Why is this error? what is the behavior of unsigned long long in x86 architecture? How to set vector size with unsigned long long value in x86 architecture?


Solution

  • Use size_t sz like a normal person, that's the arg type std::vector::resize(size_t) expects, so using the same type will mean there's no implicit conversion and thus no narrowing.

    unsigned long long is a 64-bit type, but size_t is only 32-bit, in 32-bit code.

    You can't have a std::vector larger than SIZE_MAX, so it's pointless to use a wider integer type. That's all MSVC is complaining about. It's not an error if you never actually have a huge value in sz, but you've apparently set MSVC to be really pedantic and treat warnings as errors.

    This implicit conversion is unnecessary in the first place; avoid it by using a matching type.