0
int exp1 = ((1<<31)>>31)<<32 // output changes everytime
int exp2 = ((1<<31)>>31)<<31<<1 // 0

why is this happening?

it may be caused by overflow thing, but cannot understand properly.

I am trying to solve this problem for hours, need some help

(p.s integer for 32bits)

jwkoo
  • 2,393
  • 5
  • 22
  • 35
  • You should be getting compiler errors/warnings about shifting an `int` by `32` bits. If `int` is <= 32 bits wide on your implementation, of course. – bool3max Sep 22 '18 at 12:56
  • 3
    Possible duplicate of [Why doesn't left bit-shift, "<<", for 32-bit integers work as expected when used more than 32 times?](https://stackoverflow.com/questions/7401888/why-doesnt-left-bit-shift-for-32-bit-integers-work-as-expected-when-used) – Ben Sep 22 '18 at 12:56

1 Answers1

3

Shifting by the whole type size or more is undefined behavior, so anything can happen (it comes from the fact that many architectures shift instructions have bizarre behavior in these cases). Splitting the shift in two parts works around the issue.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299