Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't unsigned variables used more often? [duplicate]

Tags:

c#

.net

It seems that unsigned integers would be useful for method parameters and class members that should never be negative, but I don't see many people writing code that way. I tried it myself and found the need to cast from int to uint somewhat annoying...

Anyhow what are you thoughts on this?

Duplicate

Why is Array Length an Int and not an UInt?

like image 600
Alex Baranosky Avatar asked Jan 29 '09 01:01

Alex Baranosky


2 Answers

The idea, that unsigned will prevent you from problems with methods/members that should not have to deal with negative values is somewhat flawed:

  • now you have to check for big values ('overflow') in case of error
    • whereas you could have checked for <=0 with signed
  • use only one signed int in your methods and you are back to square "signed" :)

Use unsigned when dealing with bits. But don't use bits today anyway, except you have such a lot of them, that they fill some megabytes or at least your small embedded memory.

like image 115
Leonidas Avatar answered Oct 26 '22 23:10

Leonidas


Using the standard ones probably avoids the casting to unsigned versions. In your code, you can probably maintain the distinction ok, but lots of other inputs and 3rd party libraries wont and thus the casting will just drive people mad!

like image 25
Simon P Avatar answered Oct 26 '22 23:10

Simon P