0

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?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Mounika
  • 371
  • 4
  • 18
  • 1
    *Why is this error?* -- [Read the documentation](https://en.cppreference.com/w/cpp/container/vector/resize). Where is `unsigned long long` specified as being the type to use? – PaulMcKenzie Nov 22 '20 at 05:54
  • Sizes are size_t, not unsigned long long – phuclv Nov 22 '20 at 05:56

1 Answers1

1

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.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • 2
    MSVC isn't complaining about the pointlessness of using a wider integer type. It's warning you about implicit integer conversions, which, in my opinion, are the biggest misfeature of the C++ language. See [the documentation for C4244](https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-levels-3-and-4-c4244). This is a warning at -W3 and -W4. You're right that the asker clearly has -Werror set, but I think you are a bit too dismissive of the utility of this warning, especially in the general case. – Cody Gray - on strike Nov 22 '20 at 06:28
  • @CodyGray: Thanks, fixed. That's what I meant (that the implicit conversion was pointless, not the warning), but of course if someone knew C++ well enough to understand my point from what I initially wrote, they wouldn't have needed to ask the question. My answer was low-effort because it was initially going to be a comment. I was hoping for a more interesting question based on the title, but vector was `std::vector` not a SIMD vector, and there was nothing x86-specific, just a platform with 32-bit `size_t`. :/ – Peter Cordes Nov 22 '20 at 06:42
  • Haha, yeah, I could sense the frustration from the very first sentence. I also chuckled. – Cody Gray - on strike Nov 22 '20 at 06:44