What is unsigned int in C: Explanation and Examples
unsigned int in C is a data type that stores only non-negative whole numbers (zero and positive integers). Unlike int, it cannot hold negative values, which allows it to represent a larger range of positive numbers using the same memory size.How It Works
Think of unsigned int as a box that can only hold zero or positive numbers. Normally, an int box can hold both positive and negative numbers, but half of its range is used for negatives. By removing the ability to store negative numbers, unsigned int uses all the space to store bigger positive numbers.
For example, if an int uses 4 bytes (32 bits), it can store numbers roughly from -2 billion to +2 billion. But an unsigned int with the same 4 bytes can store numbers from 0 up to about 4 billion. This is because it treats all bits as part of the positive number.
This is useful when you know your values will never be negative, like counting items or working with memory addresses.
Example
This example shows how unsigned int stores only positive numbers and what happens if you try to assign a negative value.
#include <stdio.h> int main() { unsigned int a = 10; printf("Value of a: %u\n", a); a = -5; // Assigning negative value to unsigned int printf("Value of a after assigning -5: %u\n", a); return 0; }
When to Use
Use unsigned int when you need to store only zero or positive numbers and want to maximize the range of values you can hold. Common cases include:
- Counting items, like number of users or objects.
- Working with sizes or lengths, such as array sizes or file sizes.
- Handling bitwise operations where negative numbers don't make sense.
However, be careful when mixing unsigned int with signed integers, as this can cause unexpected results in comparisons or calculations.
Key Points
- unsigned int stores only zero and positive whole numbers.
- It uses the same memory size as
intbut doubles the positive range. - Assigning negative values to
unsigned intcauses wrap-around to large positive numbers. - Ideal for counts, sizes, and bitwise operations.
- Be cautious mixing signed and unsigned types to avoid bugs.
Key Takeaways
unsigned int holds only non-negative integers, increasing the positive range.int but cannot represent negative numbers.unsigned int results in large positive values due to wrap-around.