When to use unsigned values over signed ones?

前端 未结 5 1239
栀梦
栀梦 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:09

    I would think that if your business case dictates that a negative number is invalid, you would want to have an error shown or thrown.

    With that in mind, I only just recently found out about unsigned integers while working on a project processing data in a binary file and storing the data into a database. I was purposely "corrupting" the binary data, and ended up getting negative values instead of an expected error. I found that even though the value converted, the value was not valid for my business case.
    My program did not error, and I ended up getting wrong data into the database. It would have been better if I had used uint and had the program fail.

提交回复
热议问题