Undefined behavior of right-shift in C++

后端 未结 2 780
一个人的身影
一个人的身影 2020-12-31 07:14

From cppreference.com:

For unsigned a and for signed a with nonnegative values, the value of a >> b is the integer part of a/2b . For neg

2条回答
  •  感情败类
    2020-12-31 07:24

    One of the goals of C++ is to allow for fast, efficient code, "close to the hardware". And on most hardware, an integer right shift or left shift can be implemented by a single opcode. The trouble is, different CPUs have different behavior in this case where the shift magnitude is more than the number of bits.

    So if C++ mandated a particular behavior for shift operations, when producing code for a CPU whose opcode behavior doesn't match all the Standard requirements, compilers would need to insert checks and logic to make sure the result is as defined by the Standard in all cases. This would need to happen to almost all uses of the built-in shift operators, unless an optimizer can prove the corner case won't actually happen. The added checks and logic would potentially slow down the program.

提交回复
热议问题