Strange behavior of bit-shift [duplicate]

2019-09-18 14:44发布

问题:

This question already has an answer here:

  • Arithmetic right shift gives bogus result? 2 answers
  • Is right shift undefined behavior if the count is larger than the width of the type? 2 answers

Can't understand behavior of this bit shift:

int container = 1;

cout<<(container>>32)<<endl;

If it's logical shift the output should be 0, but it's 1 instead, as if it was cyclic shift. When looking at disassembly I see that command used is SAR. Please explain this behavior to me.

回答1:

You shifted a 32-bit number by 32, which results in undefined behavior, and the resulting 1 is a coincidence.