常规算术转换跨平台类型差异:Windows下如何得到long类型结果?
解决Windows平台下有符号/无符号整数运算结果为long的问题
问题根源
Windows平台中long为32位,与unsigned int(同样32位)的类型秩相同。根据C++常规算术转换规则:当有符号类型和无符号类型的秩相等时,运算会统一转换为无符号类型,因此1L + 1U的结果是unsigned long。而Linux平台的long是64位,秩高于32位的unsigned int,所以运算结果会保留为long。
具体解决方法
1. 手动强制转换无符号操作数为long
直接将无符号操作数显式转换为long类型,确保两个运算数均为long,结果自然为long:
#include <typeinfo> #include <cassert> #include <iostream> int main() { assert(typeid(1L + static_cast<long>(1U)) == typeid(long)); std::cout << typeid(1L + static_cast<long>(1U)).name(); }
也可以使用C风格转换(可读性较差,不推荐):(long)1U。
2. 使用更宽的有符号类型替代long
将long替换为long long(Windows和Linux均为64位),其类型秩高于unsigned int,运算结果会是long long。若需要long类型,可在运算后再转换(注意数值溢出风险):
#include <typeinfo> #include <cassert> #include <iostream> int main() { long result = 1LL + 1U; assert(typeid(result) == typeid(long)); std::cout << typeid(result).name(); }
内容的提问来源于stack exchange,提问作者zturn
相关产品推荐
相关产品推荐

