当我编写以下程序并使用GNU C++编译器时,1我认为输出是由编译器执行的旋转操作引起的.
#include <iostream>
int main()
{
int a = 1;
std::cout << (a << 32) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但从逻辑上讲,正如所说的那样,如果位溢出位宽就会丢失,输出应为0.发生了什么?
代码在ideone上,http: //ideone.com/VPTwj .
我最近使用右移运算符遇到了一种奇怪的行为.
以下程序:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stdint.h>
int foo(int a, int b)
{
return a >> b;
}
int bar(uint64_t a, int b)
{
return a >> b;
}
int main(int argc, char** argv)
{
std::cout << "foo(1, 32): " << foo(1, 32) << std::endl;
std::cout << "bar(1, 32): " << bar(1, 32) << std::endl;
std::cout << "1 >> 32: " << (1 >> 32) << std::endl; //warning here
std::cout << "(int)1 >> (int)32: " << ((int)1 …Run Code Online (Sandbox Code Playgroud) 如果你有一些变量(在堆栈上),你左或右位移超过它的结束会发生什么?
即
byte x = 1;
x >> N;
Run Code Online (Sandbox Code Playgroud)
如果x是一个指向内存转换为字节的指针而你做同样的事情怎么办?
byte* x = obtain pointer from somewhere;
*x = 1;
*x >> N;
Run Code Online (Sandbox Code Playgroud)