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:

TypeStorage Size
short2 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

</>
Copy
#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:

  1. We declare three short variables: num1, num2, and sum.
  2. We assign values 150 and -32000 to num1 and num2 respectively.
  3. The sum of these two numbers is stored in the sum variable.
  4. We print the values of num1, num2, and sum using printf().

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

</>
Copy
#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 SizeMinimum ValueMaximum Value
2 bytes-32,76832,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

</>
Copy
#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:

  1. Its ability to store small whole numbers (both positive and negative).
  2. Its typical storage size of 2 bytes.
  3. How to get the storage size programmatically using sizeof().
  4. The minimum and maximum values that short can store.
  5. How to retrieve these values using limits.h.