短整数的原始操作
primitive operations with short integers
考虑一个代码
int16_t x = 1;
int16_t y = 1;
auto v = x + y;
int16_t w = x + y;
cout << sizeof(v) << endl << sizeof(w) << endl;
其中我使用 #include <cstdint>
表示固定大小的整数。
输出是
4
2
为什么 v 和 w 的大小不同,如何在原始操作期间固定整数的大小?
请注意,如果我使用 8 位整数类型而不是 int16_t,v 的结果将是相同的。
如 http://en.cppreference.com/w/cpp/language/implicit_cast 所述:
Prvalues of small integral types (such as char
may be converted to prvalues of larger integral types (such as int
). In particular, arithmetic operators do not accept types smaller than int
as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable. This conversion always preserves the value.
[强调我的; link 移除]
所以没有办法如你所愿
int16_t w = x + y;
起作用的原因是它在最后转换回 int16_t
。来自同一来源:
If the destination type is signed, the value does not change if the source integer can be represented in the destination type. Otherwise the result is implementation-defined. (Note that this is different from signed integer arithmetic overflow, which is undefined)
[link 已删除]
编辑添加: 也就是说,我应该提一下,也没有真正的理由去做你想做的事。 int16_t w = x + y;
确实意味着 int16_t w = static_cast<int16_t>( static_cast<int>(x) + static_cast<int>(y) );
而不是开始时执行 16 位加法;但无论哪种方式,结果都是一样的。唯一的区别是,如果 x + y
在 16 位整数的范围之外,那么 int16_t w = x + y;
仍然表现良好(给出实现定义的结果),因为 +
本身未触发溢出。
考虑一个代码
int16_t x = 1;
int16_t y = 1;
auto v = x + y;
int16_t w = x + y;
cout << sizeof(v) << endl << sizeof(w) << endl;
其中我使用 #include <cstdint>
表示固定大小的整数。
输出是
4
2
为什么 v 和 w 的大小不同,如何在原始操作期间固定整数的大小?
请注意,如果我使用 8 位整数类型而不是 int16_t,v 的结果将是相同的。
如 http://en.cppreference.com/w/cpp/language/implicit_cast 所述:
Prvalues of small integral types (such as
char
may be converted to prvalues of larger integral types (such asint
). In particular, arithmetic operators do not accept types smaller thanint
as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable. This conversion always preserves the value.
[强调我的; link 移除]
所以没有办法如你所愿
int16_t w = x + y;
起作用的原因是它在最后转换回 int16_t
。来自同一来源:
If the destination type is signed, the value does not change if the source integer can be represented in the destination type. Otherwise the result is implementation-defined. (Note that this is different from signed integer arithmetic overflow, which is undefined)
[link 已删除]
编辑添加: 也就是说,我应该提一下,也没有真正的理由去做你想做的事。 int16_t w = x + y;
确实意味着 int16_t w = static_cast<int16_t>( static_cast<int>(x) + static_cast<int>(y) );
而不是开始时执行 16 位加法;但无论哪种方式,结果都是一样的。唯一的区别是,如果 x + y
在 16 位整数的范围之外,那么 int16_t w = x + y;
仍然表现良好(给出实现定义的结果),因为 +
本身未触发溢出。