Mo fang Mo fang - 1 year ago 83
C++ Question

How to initialize a vector with -2147483648 in C++

I found the problem when initializing a vector with value -2147483648

vector<int> vec1({-2147483648}); // invalid, error C2440
vector<int> vec2({0, -2147483648}); // invalid, error C2398
int a = -2147483648;
vector<int> vec3({t}); // valid
vector<int> vec4({0, t}); // valid
vector<int> vec5(1, -2147483648); // valid

The problem appears when I use VS2013. Does anyone know why?

Answer Source

-2147483648 is a unary negation operator applied to an integral literal 2147483648. The latter does not fit into an int (assuming it's 32-bit), which means that -2147483648 is actually an expression of unsigned type.

Now, unsigned can be implicitly converted to int (when the value is unrepresentable, the result is technically implementation-defined, but usually unsurprising). However, this is a narrowing conversion, which is prohibited when used with brace initialization.

Instead of attempting to write the value as a literal, just use INT_MIN from the <limits.h> header, or std::numeric_limits<int>::min() from the <limits> header, assuming that your intention is to express the minimum value of an int.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download