Search code examples
cunsigned-integer

Signed integer and unsigned integer


I am studying c language and there are two different integer types, signed/unsigned.

Signed integers can present both positive and negative numbers. Why do we need unsigned integers then?


Solution

  • One word answer is "range"!

    When you declare a signed integer, it takes 4 bytes/ 32 bits memory (on a 32 bit system). Out of those 32 bits, 1 bit is for sign and other 31 bits represent number. Means you can represent any number between -2,147,483,648 to 2,147,483,647 i.e. 2^31.

    What if you want to use 2,147,483,648? Go for 8 bytes? But if you are not interested in negative numbers, then isn't it wastage of 4 bytes?

    If you use unsigned int, all 32bits represent your number as you don't need to spare 1 bit for sign. Hence, with unsigned int, you can go from 0 to 4,294,967,295 i.e. 2^32

    Same applies for other data types.