C unsigned int Data Type

In C, the unsigned int data type is used to store non-negative whole numbers. Unlike the standard int type, which can hold both positive and negative numbers, unsigned int only stores positive values and extends the upper range of numbers it can hold.

The unsigned int data type is useful for cases where negative values are not needed, such as storing counts, sizes, or non-negative IDs.


1. Storage Size of unsigned int Data Type

The storage size of an unsigned int depends on the system architecture and compiler, similar to int. Typically:

TypeStorage Size
unsigned int2 or 4 bytes

On 16-bit systems, an unsigned int usually takes 2 bytes, whereas on 32-bit and 64-bit systems, it typically occupies 4 bytes.

2. Values Stored by unsigned int Data Type

The unsigned int data type stores only positive whole numbers, starting from 0. It cannot store negative values.

Example values that can be stored in unsigned int:

0, 100, 50000, 4294967295

3. Example: Declaring and Using unsigned int Variables

Let’s see a simple program that demonstrates how to declare and use unsigned int variables in C.

main.c

</>
Copy
#include <stdio.h>

int main() {
    unsigned int age = 25;
    unsigned int population = 100000;

    printf("Age: %u\n", age);
    printf("Population: %u\n", population);

    return 0;
}

Explanation:

  1. We declare two unsigned int variables: age and population.
  2. We assign positive values to both variables.
  3. We use printf() with the format specifier %u to print unsigned int values.

Output:

Age: 25
Population: 100000

4. Checking Storage Size of unsigned int Programmatically

We can determine the storage size of an unsigned int using the sizeof operator.

main.c

</>
Copy
#include <stdio.h>

int main() {
    printf("Size of unsigned int: %lu bytes\n", sizeof(unsigned int));
    return 0;
}

Output (varies based on system architecture):

Size of unsigned int: 4 bytes

5. Minimum and Maximum Values of unsigned int

Since unsigned int only holds non-negative values, its range starts from 0 and extends to a higher maximum value than a signed int of the same size.

Storage SizeMinimum ValueMaximum Value
2 bytes065,535
4 bytes04,294,967,295

6. Getting Maximum Value of unsigned int Programmatically

The maximum value of an unsigned int can be retrieved using limits.h.

main.c

</>
Copy
#include <stdio.h>
#include <limits.h>

int main() {
    printf("Maximum unsigned int value: %u\n", UINT_MAX);
    return 0;
}

Output:

Maximum unsigned int value: 4294967295

Conclusion

In this tutorial, we explored the unsigned int data type in C, including:

  1. Its ability to store only non-negative whole numbers.
  2. Its typical storage size of 2 or 4 bytes, depending on the system.
  3. How to get the storage size programmatically using sizeof().
  4. The minimum and maximum values it can store.
  5. How to retrieve the maximum value using limits.h.