简体   繁体   中英

Integer promotion between unsigned and int

Here

std::string s{ "aa" }; 
s.length() - 3;  // == very large number

From memory, C's integer promotion rules (idk about C++) produce a type wide enough to fit the result of the calculation and favour unsigned types (for the extra bit of width). But 3 is of type int (right?). So why is the result of type unsigned instead of int or long ? unsigned is certainly not wide enough to capture the result of the expression!

string::length has type size_t . For x86-64 platforms modern compilers define size_t as uint64_t . Therefore 3 is promoted to uint64_t . Compiler can not promote it to long or even long long (aka int64_t ) because, for example, (1<<64) - 2 can not be represented in signed 64-bit integer. As mentioned in comments, there is string::ssize in C++20 for signed size value.

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