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

The `sizeof` operator with types

The sizeof operator with types

What you'll learn: How to use the sizeof operator to determine exactly how many bytes of memory a specific data type occupies on your computer.

Measuring the Containers

In C, different types of data need different amounts of room. Think of data types like storage containers: a char is like a small shoebox, while a double is more like a large filing cabinet. However, the exact size of these "containers" isn't always the same on every computer. A long might be 4 bytes on one machine and 8 bytes on another.

To write code that works everywhere, you shouldn't guess how much space a type takes. Instead, you use the sizeof operator. It acts like a digital tape measure, telling you the size of a type in bytes.

Using sizeof with Type Names

When you want to check the size of a specific data type (rather than a specific variable), you place the name of the type inside parentheses immediately after the keyword.

Here is how it looks in practice:

#include <stdio.h>

int main() {
    // We use %zu because sizeof returns a value of type size_t
    printf("A char takes up %zu byte\n", sizeof(char));
    printf("An int takes up %zu bytes\n", sizeof(int));
    printf("A float takes up %zu bytes\n", sizeof(float));
    printf("A double takes up %zu bytes\n", sizeof(double));

    return 0;
}

Why Parentheses Matter

You might see some programmers use sizeof without parentheses when they are measuring a variable (like sizeof myVariable). However, when you are measuring a data type directly (like int or float), the parentheses are mandatory.

Think of it like a function call to the compiler: you are asking, "Hey, how much room do you need to store one of these?" The compiler calculates this during the building process, so it doesn't slow down your program while it's running.

Why Do We Need This?

Using sizeof ensures your programs are "portable." If you assume an integer is always 4 bytes and move your code to a specialized system where it is 2 bytes, your program might crash or behave strangely. By using sizeof(int), you let the compiler handle the math for you, ensuring your code fits perfectly on any hardware.

Key takeaway

Use sizeof(type) to find the memory footprint of a data type in bytes, ensuring your code adapts to different computer architectures.