Should I use unsigned integers for counting members?

前端 未结 6 1964
自闭症患者
自闭症患者 2021-02-04 14:25

Should I use unsigned integers for my count class members?

Answer

For example, assume a class

TList  = class
private
           


        
6条回答
  •  伪装坚强ぢ
    2021-02-04 14:57

    Don't.

    It's not just going against a programming idiom, it's an explicit request to the compiler to use unsigned arithmetic, that is either prone to anomalous behaviors (if you don't guard against overflows) or to irrelevant runtime exceptions (if you guard against overflows, a temporary overflow will be fatal, f.i when you subtract before adding, even if the final result is positive, and I'm referring to the CPU opcode-level ordering of operations, which may not bear a trivial relationship to what you have in your code).

    Keep in mind "unsigned" does not translate to "positive", it translates to "doesn't have a sign", which is different. The term "unsigned" was picked for good reason (and naming it "Cardinal" in Delphi was a poor choice IMO).

    Unsigned types are for raw storage specifications, bitwise operations, ASM code, embedded controllers and other specialty uses. When you're doing high-level programming, you should forget you ever heard about unsigned types.

提交回复
热议问题