Why int plus uint returns uint?

前端 未结 3 1372
生来不讨喜
生来不讨喜 2020-12-20 13:14

int plus unsigned int returns an unsigned int. Should it be so?

Consider this code:

#include 
#include 

        
3条回答
  •  一向
    一向 (楼主)
    2020-12-20 13:43

    It is likely that the behavior stems from the logic behind pointer types (memory location, e.g. std::size_t) plus a memory location difference (std::ptrdiff_t) is also a memory location.

    In other words, std::size_t = std::size_t + std::ptrdiff_t.

    When this logic is translated to underlaying types this means, unsigned long = unsigned long + long, or unsigned = unsigned + int.

    The "other" explanation from @supercat is also possibly correct.

    What is clear is that unsigned integer were not designed or should not be interpreted to be mathematical positive numbers, no even in principle. See https://www.youtube.com/watch?v=wvtFGa6XJDU

提交回复
热议问题