Calculating Ranges of Data Types in C

前端 未结 5 2106
眼角桃花
眼角桃花 2020-12-05 22:02

I\'m working through K&R Second Edition, and can\'t figure out why I\'m getting a certain result. The problem I\'m solving is calculating upper and lower limits for data

5条回答
  •  误落风尘
    2020-12-05 22:47

    When you perform the bit shift on i, the compiler sees that i is a signed quantity, and performs an arithmetic right shift. It seems like you want that line of code to perform a logical right shift.

    Change the line

    i >>= 1;

    to

    i = ((unsigned int)i) >> 1;

    Then it works!

    Output:
    Upper limit: 2147483647
    Lower limit: -2147483648
    

提交回复
热议问题