简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM