C++位移位在相反方向上具有相同的常量,结果不同,代码更改很小
C++ Bit Shift With Same Constant in Opposite Directions, Different Result With Minor Code Changes
>我有一个模板函数
template< uint8_t HOW_FAR_CONSTANT, uint8_t START_CONSTANT, uint8_t ORIGINAL_CONSTANT>
uint8_t Foo();
在Foo
我做了这样的事情
const uint8_t OFFSET_CONSTANT = ( START_CONSTANT + HOW_FAR_CONSTANT );
const uint8_t RESULT_CONSTANT = ( ( ORIGINAL_CONSTANT << OFFSET_CONSTANT ) >> OFFSET_CONSTANT );
它不会截断位,它会导致:
ORIGINAL: 10101010
RESULT: 10101010
但是,如果我稍作修改
const uint8_t OFFSET_CONSTANT = ( START_CONSTANT + HOW_FAR_CONSTANT );
const uint8_t RESULT_0_CONSTANT = ( ORIGINAL_CONSTANT << OFFSET_CONSTANT );
const uint8_t RESULT_CONSTANT = ( RESULT_0_CONSTANT >> OFFSET_CONSTANT );
我得到
ORIGINAL: 10101010
RESULT 0 (lets say OFFSET_CONSTANT is 2): 10101000
RESULT: 00101010
我想知道这是否是一个糟糕的编译器优化。谁能解释一下?
更新:
在编译器资源管理器上尝试了这个,它绝对是标准行为,而且编译器优化还不错。
两者都没有优化。由于在类型为uint8_t
的对象中存储移位操作的结果而存在截断。
const uint8_t RESULT_0_CONSTANT = ( ORIGINAL_CONSTANT << OFFSET_CONSTANT );
执行移位操作时,积分提升将应用于操作数。
所以在这个表达中
const uint8_t RESULT_CONSTANT = ( ( ORIGINAL_CONSTANT << OFFSET_CONSTANT ) >> OFFSET_CONSTANT );
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
子表达式( ORIGINAL_CONSTANT << OFFSET_CONSTANT )
的类型为int
而不是uint8_t
。
从C++标准(5.8 班运算符(
- 1 换档操作员从左到右<<和>>分组。操作数应为整型或无作用域枚举类型,并执行整型升级。
相关文章:
- 这两个代码片段相似,但显示的结果不同
- 为什么第二个代码给出了预期的结果,而第一个代码却没有?
- RapidXML - 代码创建意外结果
- 代码未在联机编译器上显示结果
- 为什么这两段使用 constexpr、__PRETTY_FUNCTION__ 和 char * 的代码有不同的结果?
- C++位移位在相反方向上具有相同的常量,结果不同,代码更改很小
- 我的代码厨师提交显示错误的结果
- 如何查找导致结果不一致的代码
- 如何使用 c++ 将股票代码的结果添加到 poloniex 中的数组中?
- 我无法弄清楚我的代码未显示预期结果的问题
- 为什么这段代码(在 Matlab 的 MEX 文件中使用 OpenMP)给出不同的结果?
- 为什么这两个相似的代码计算行列式的结果不同?
- 为什么这个C++程序在代码::块和在线 IDE 之间返回不同的结果?
- C++:汇编代码包含断言结果
- 有人可以解释一下'sizeof'在此代码中返回的结果吗
- 相同的代码在联机 IDE 和本地 IDE 中给出不同的结果
- 来自 open() 的返回结果代码之间的差异:25 与 3
- 我不小心没有使用std::ref——结果代码做了什么?
- Typename给出了奇怪的输入结果代码块
- 用c++运行一个进程,过滤输出,获取结果代码,同时获取系统错误