Is using unsigned integer overflow good practice?

后端 未结 12 534
耶瑟儿~
耶瑟儿~ 2020-12-01 15:55

I was reading the C Standard the other day, and noticed that unlike signed integer overflow (which is undefined), unsigned integer overflow is well defined. I\'ve seen it us

12条回答
  •  暖寄归人
    2020-12-01 16:53

    I would suggest always having an explicit cast any time one is going to rely upon unsigned numbers wrapping. Otherwise there may be surprises. For example, if "int" is 64 bits, code like:

    UInt32 foo,bar;
    if ((foo-bar) < 100) // Report if foo is between bar and bar+99, inclusive)
      ... do something
    

    may fail, since "foo" and "bar" would get promoted to 64-bit signed integers. Adding a typecast back to UInt32 before checking the result against 100 would prevent problems in that case.

    Incidentally, I believe the only portable way to directly get the bottom 32 bits of the product of two UInt32's is to cast one of the ints to a UInt64 prior to doing the multiply. Otherwise the UInt32's might be converted to signed Int64's, with the multiplication overflowing and yielding undefined results.

提交回复
热议问题