c++ - 当您将位移超出变量的末尾时会发生什么?

标签 c++ c bit-manipulation

如果你有一些变量(在堆栈上)并且你向左或向右移动超出其末尾会发生什么?

byte x = 1;
x >> N;

如果 x 是指向内存的指针并转换为字节,而您做同样的事情会怎样?

byte* x = obtain pointer from somewhere;
*x = 1;
*x >> N;

最佳答案

它不会(必然)变为零。行为未定义(C99 §6.5.7,“移位运算符”):

If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

(C++0x §5.8,“移位运算符”):

The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

被转移的值的存储对此没有任何影响。

关于c++ - 当您将位移超出变量的末尾时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4330282/

相关文章:

c++ - Microsoft Visual Studio 编写C语言

C++ 在输入中查找字符串并使用运算符

c++ - 基于静态成员类型的模板函数特化

c - 在 C 中暂停线程一秒钟

C - 使用 Controller 函数的 Pthreads

c - 可变修改类型只是 VLA 吗?

c++ - 函数 getValue(s) cplex c++ 的问题

c++ - 是否有仅从零增加到一的按位技巧?

c - 使用按位运算符时出现段错误

c++ - 如何处理位字段中的单位( bool )成员?