C short Data Type
In C, the short
data type is an integer type that requires less memory than a regular int
. It is used when we need to store small integer values while optimizing memory usage.
The short
data type is useful for memory-efficient programs where smaller integer values are sufficient.
1. Storage Size of short
Data Type
The storage size of the short
data type depends on the system and compiler, but typically:
Type | Storage Size |
---|---|
short | 2 bytes |
On most modern systems, a short
integer occupies 2 bytes, allowing it to store a smaller range of integer values compared to an int
.
2. Values Stored by short
Data Type
The short
data type stores whole numbers (integers), including both positive and negative values. It does not support decimal or fractional numbers.
Example values that can be stored in short
:
100, -200, 32767, -32768
3. Example: Declaring and Using short
Variables
Let’s look at an example of how to declare and use short
variables in C.
main.c
#include <stdio.h>
int main() {
short num1 = 150;
short num2 = -32000;
short sum = num1 + num2;
printf("Number 1: %d\n", num1);
printf("Number 2: %d\n", num2);
printf("Sum: %d\n", sum);
return 0;
}
Explanation:
- We declare three
short
variables:num1
,num2
, andsum
. - We assign values 150 and -32000 to
num1
andnum2
respectively. - The sum of these two numbers is stored in the
sum
variable. - We print the values of
num1
,num2
, andsum
usingprintf()
.
Output:
Number 1: 150
Number 2: -32000
Sum: -31850
4. Checking Storage Size of short
Programmatically
We can determine the storage size of short
in bytes using the sizeof
operator.
main.c
#include <stdio.h>
int main() {
printf("Size of short: %lu bytes\n", sizeof(short));
return 0;
}
Output (varies based on system architecture):
Size of short: 2 bytes
5. Minimum and Maximum Values of short
The range of values a short
can store depends on its size:
Storage Size | Minimum Value | Maximum Value |
---|---|---|
2 bytes | -32,768 | 32,767 |
6. Getting Maximum and Minimum Values of short
Programmatically
The maximum and minimum values of a short
can be retrieved using limits.h
.
main.c
#include <stdio.h>
#include <limits.h>
int main() {
printf("Minimum short value: %d\n", SHRT_MIN);
printf("Maximum short value: %d\n", SHRT_MAX);
return 0;
}
Output:
Minimum short value: -32768
Maximum short value: 32767
Conclusion
In this tutorial, we explored the short
data type in C, including:
- Its ability to store small whole numbers (both positive and negative).
- Its typical storage size of 2 bytes.
- How to get the storage size programmatically using
sizeof()
. - The minimum and maximum values that
short
can store. - How to retrieve these values using
limits.h
.