When to use unsigned values over signed ones?

前端 未结 5 1240
栀梦
栀梦 2020-11-27 04:53

When is it appropriate to use an unsigned variable over a signed one? What about in a for loop?

I hear a lot of opinions about this and I wanted to see

5条回答
  •  粉色の甜心
    2020-11-27 05:16

    I was glad to find a good conversation on this subject, as I hadn't really given it much thought before.

    In summary, signed is a good general choice - even when you're dead sure all the numbers are positive - if you're going to do arithmetic on the variable (like in a typical for loop case).

    If you're going to do bitwise things like masks, unsigned starts to make more sense. Or, if you're desperate to get that extra positive range by taking advantage of the sign bit.

    Personally, I like signed because I don't trust myself to stay consistent and avoid mixing the two types (like the article warns against).

提交回复
热议问题