C unsigned short
Data Type
In C, the unsigned short
data type is used to store non-negative integer values within a limited range. Unlike the standard short
type, which can store both positive and negative values, unsigned short
can only store positive values, effectively doubling its upper limit.
The unsigned short
data type is useful when dealing with small positive integer values while conserving memory.
1 Storage Size of unsigned short
Data Type
The size of an unsigned short
varies depending on the system architecture and compiler, but it typically follows this pattern:
Type | Storage Size |
---|---|
unsigned short | 2 bytes (16 bits) |
On most systems, an unsigned short
occupies 2 bytes, allowing it to store integer values ranging from 0
to 65,535
.
2 Values Stored by unsigned short
Data Type
The unsigned short
data type stores only non-negative whole numbers (i.e., no decimals or fractions).
Example values that can be stored in unsigned short
:
0, 100, 25000, 65535
3 Example: Declaring and Using unsigned short
Variables
Let’s see a simple program demonstrating how to declare and use unsigned short
variables in C.
main.c
#include <stdio.h>
int main() {
unsigned short num1 = 500;
unsigned short num2 = 60000;
unsigned short sum = num1 + num2;
printf("Number 1: %u\n", num1);
printf("Number 2: %u\n", num2);
printf("Sum: %u\n", sum);
return 0;
}
Explanation:
- We declare three
unsigned short
variables:num1
,num2
, andsum
. - We assign values
500
and60000
tonum1
andnum2
, respectively. - The sum of these two numbers is stored in the
sum
variable. - We print the values using
printf()
, using the%u
format specifier, which is used for unsigned integers.
Output:
Number 1: 500
Number 2: 60000
Sum: 60500
4 Checking Storage Size of unsigned short
Programmatically
We can determine the storage size of an unsigned short
using the sizeof
operator.
main.c
#include <stdio.h>
int main() {
printf("Size of unsigned short: %lu bytes\n", sizeof(unsigned short));
return 0;
}
Output:
Size of unsigned short: 2 bytes
5 Minimum and Maximum Values of unsigned short
Since unsigned short
only stores non-negative values, its range is:
Storage Size | Minimum Value | Maximum Value |
---|---|---|
2 bytes (16 bits) | 0 | 65,535 |
6 Getting Maximum and Minimum Values of unsigned short
Programmatically
The maximum and minimum values of an unsigned short
can be retrieved using limits.h
.
main.c
#include <stdio.h>
#include <limits.h>
int main() {
printf("Minimum unsigned short value: %u\n", 0);
printf("Maximum unsigned short value: %u\n", USHRT_MAX);
return 0;
}
Output:
Minimum unsigned short value: 0
Maximum unsigned short value: 65535
Conclusion
In this tutorial, we explored the unsigned short
data type in C, including:
- Its ability to store only positive whole numbers.
- Its typical storage size of 2 bytes (16 bits).
- How to get the storage size programmatically using
sizeof()
. - The minimum and maximum values it can store.
- How to retrieve these values using
limits.h
.