Course contentsShow
← C
Lesson 82 of 1,2192. Variables and TypesFree lesson

Short vs. Long integers

Short vs. Long integers

What you'll learn: How to choose between different sizes of integer types to balance memory usage and numerical range.

The Suitcase Analogy

Imagine you are packing for a trip. If you are only bringing a pair of socks, you use a small pouch. If you are packing for a month-long expedition, you need a giant trunk.

In C, variables are like these containers. While int is your standard, "medium-sized" suitcase, C provides short and long to help you be more efficient with your computer’s memory.

Short: The Space-Saver

A short integer is designed to take up less memory (usually 2 bytes). Because it is smaller, it can’t hold very large numbers. On most systems, a short can only count up to about 32,767.

You would use a short if you are writing a program for a device with very little memory—like a microwave controller—or if you have a massive list of small numbers, like the ages of a million students.

Long: The Heavy Lifter

A long integer is the giant trunk. It uses more memory (usually 4 or 8 bytes) to store much larger values. If you are calculating the population of the world or the number of kilometers to another star, a standard int might "overflow" and give you a nonsensical negative number. A long provides the extra room needed for these massive figures.

Code Example

Here is how you declare these types in C. Notice that we use different "format specifiers" like %hd and %ld to tell the printf function which size we are using.

#include <stdio.h>

int main() {
    // A small container for small numbers
    short age = 25;
    
    // The standard container
    int score = 45000;
    
    // A large container for big numbers
    long globalDebt = 307000000000000L;

    printf("Short: %hd\n", age);
    printf("Int: %d\n", score);
    printf("Long: %ld\n", globalDebt);

    return 0;
}

When to use which?

In modern desktop programming, we mostly use int. However, if you know a number will stay small and you have millions of them, short saves RAM. If you know a number will exceed 2 billion, you must upgrade to long to prevent your program from crashing or behaving incorrectly.

Key takeaway

Use short to save memory for small numbers and long to provide enough room for massive numbers.