c++ - why does left shift with variables generate different result from that with constant? -
after compiling code below, got weird result, =1 while b =0. explain what's going on behind scene?
#include<iostream> using namespace std; int main(){ int n=32; int a=1<<n; //turns out a=1 int b=1<<32; //turns out b=0 cout<<"a="<<a<<endl; cout<<"b="<<b<<endl; }
the standard not define, or rather, defines "undefined behaviour", happens in case left shift beyond size of integer type. [the reason undefined behaviour different hardware may or may not behave same given, example, 32-bit shift left].
in first case [at least without optimization], compiler generates instructions calculate 1 << 32
- on x86 turns 1 << (32 & 31)
same 1 << 0
- 1.
in second case, compiler calculate value itself, turns overflow, , gives zero.
it's quite (but not certain) if change compiler options optimize code, gives 0 both cases. , going behaviour want if loop of smaller shifts (although may find "intersting" behaviour fact number turns negative, best use unsigned shift operations, really).
Comments
Post a Comment