Lesson 36 +10 XP

Memory Size and sizeof

Memory Size and sizeof

Every object takes up memory, and the amount matters. C gives you a tool to ask exactly how much: the sizeof operator.

sizeof returns bytes

printf("%d\n", sizeof(int));      // 4 on most machines
printf("%d\n", sizeof(double));   // 8
printf("%d\n", sizeof(char));     // 1

It works on variables too

int x;
printf("%d\n", sizeof(x));   // same as sizeof(int)

A typical result

On a modern 64-bit machine:

Typesizeof
char1
int4
float4
double8

Why sizes can vary

The C standard sets minimum sizes, not exact ones. A long might be 4 bytes on one machine and 8 on another. That's why sizeof exists - instead of guessing, ask.

sizeof is compile-time

sizeof is evaluated while compiling, not while running. No runtime cost at all.

TL;DR

  • sizeof returns the size of a type or variable in bytes.
  • sizeof(int) gives the bytes of an int.
  • Typical sizes: char 1, int 4, double 8.
  • Sizes vary by machine - the standard only sets minimums.
  • sizeof is computed at compile time.