问
一个经典问题:
1unsigned int a = ...;
2long b = ...;
3auto c = a + b; // 此处 auto 会推导出什么类型?
答
写了段粗糙的测试代码:
1#include <iostream>
2#include <typeinfo>
3
4int main()
5{
6 unsigned int var_a = 4;
7 long var_b = 5;
8 auto var_c = var_a + var_b;
9 ::std::cout << "var_a: " << typeid(var_a).name() << ::std::endl;
10 ::std::cout << "var_a: " << sizeof(var_a) << ::std::endl;
11 ::std::cout << "var_b: " << typeid(var_b).name() << ::std::endl;
12 ::std::cout << "var_b: " << sizeof(var_b) << ::std::endl;
13 ::std::cout << "var_c: " << typeid(var_c).name() << ::std::endl;
14 ::std::cout << "var_c: " << sizeof(var_c) << ::std::endl;
15}
编译成 64 位代码:
1g++ main.cpp && ./a.out | c++filt -t
1var_a: unsigned int
2var_a: 4
3var_b: long
4var_b: 8
5var_c: long
6var_c: 8
编译出 32 位代码:
1g++ -m32 main.cpp && ./a.out | c++filt -t
1var_a: unsigned int
2var_a: 4
3var_b: long
4var_b: 4
5var_c: unsigned long
6var_c: 4
可见,在 32 位平台上,long
与 int
都是 4 个 bytes,long
的取值范围无法覆盖 unsigned int
,从而使得 long + unsigned int = unsigned long
。而对于 64 位平台来说,long
是 8 个 bytes,其取值范围可以覆盖 unsigned int
,因此 long + unsigned int = long
。
参考资料:
- Fundamental types ,cppreference.com