当你移位超出了变量的末尾,会发生什么? [英] What happens when you bit shift beyond the end of a variable?

查看:146
本文介绍了当你移位超出了变量的末尾,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一些变量(在堆栈),你向左或向右位移位超出其到底发生了什么?

 字节x = 1;
X - GT;> N;

如果x是一个指向内存的指针强制转换为字节和你做同样的事情?

 字节* X =从某处获得的指针;
* X = 1;
* X>> N;


解决方案

它不(一定)变成零。该行为是不确定的(C99§6.5.7,按位移位运算符):


  

如果右操作数的值
  负值或大于或等于
  以推广左侧的宽度
  操作数,行为是不确定的。


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


  

该行为是如果有合适的未定义
  操作数是负的,或大于
  或等于在的位长度
  促进左操作数。


被移位的值的存储有任何这没有影响

If you have some variable (on the stack) and you left or right bit shift beyond its end what happens?

i.e.

byte x = 1;
x >> N;

What if x is a pointer to memory cast to a byte and you do the same thing?

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

解决方案

It does not (necessarily) become zero. The behavior is undefined (C99 §6.5.7, "Bitwise shift operators"):

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, "Shift operators"):

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.

The storage of the value being shifted has no effect on any of this.

这篇关于当你移位超出了变量的末尾,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆