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:
Type | Storage Size |
---|---|
unsigned int | 2 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
#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:
- We declare two
unsigned int
variables:age
andpopulation
. - We assign positive values to both variables.
- We use
printf()
with the format specifier%u
to printunsigned 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
#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 Size | Minimum Value | Maximum Value |
---|---|---|
2 bytes | 0 | 65,535 |
4 bytes | 0 | 4,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
#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:
- Its ability to store only non-negative whole numbers.
- Its typical storage size of 2 or 4 bytes, depending on the system.
- How to get the storage size programmatically using
sizeof()
. - The minimum and maximum values it can store.
- How to retrieve the maximum value using
limits.h
.