Course contentsShow
← C
Lesson 236 of 1,2193. Operators and ExpressionsFree lesson

The `sizeof` operator with variables

The sizeof operator with variables

What you'll learn: How to use the sizeof operator to determine the exact memory footprint of a variable in your program.

The Digital Measuring Tape

Imagine you are moving into a new apartment. Before you buy a rug or a sofa, you need to know exactly how much floor space you have. In C, memory is your floor space. Every time you create a variable, the computer sets aside a specific number of "tiles" (bytes) to store that data.

The sizeof operator is your digital measuring tape. It tells you exactly how many bytes of memory a specific variable is currently occupying. Because different computers and compilers might allocate slightly different amounts of space for a standard int or double, sizeof is the most reliable way to check the "size" of your data.

Measuring Variables in Action

Unlike functions you might have seen, sizeof doesn't require a special library. It is a built-in part of the C language. When you use it on a variable, it returns a value representing bytes.

#include <stdio.h>

int main() {
    int age = 25;
    double salary = 50000.50;
    char grade = 'A';

    // We use %zu to print the result of sizeof
    printf("The size of 'age' is: %zu bytes\n", sizeof(age));
    printf("The size of 'salary' is: %zu bytes\n", sizeof(salary));
    printf("The size of 'grade' is: %zu bytes\n", sizeof(grade));

    return 0;
}

In this code, sizeof(age) looks at the variable age, sees that it is an integer, and returns the number of bytes your system uses for integers (usually 4).

Why Variable Size Matters

You might wonder, "Why do I care how big a variable is?" As you advance in C, you will eventually work with "buffers" and manual memory management. If you try to shove 8 bytes of data into a variable that only has 4 bytes of room, you’ll cause a crash or a security bug—much like trying to fit a king-sized bed into a closet.

By using sizeof on the variable itself, your code becomes "portable." This means if you move your code from a small smartwatch to a powerful desktop, sizeof will automatically adjust to the correct measurements of that specific system, ensuring your program stays stable and efficient.

Key takeaway

The sizeof operator tells you the physical memory space (in bytes) a variable occupies, ensuring you never "overfill" your data containers.