Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Keywords and Statements

The sizeof operator

Reference for C sizeof: size in bytes of types and objects, the size_t result, array length idiom, decay in parameters, padding and VLAs.

sizeof yields the size, in bytes, of a type or of the type of an expression. The result has type size_t and is a constant evaluated at compile time, except for variable length arrays, where it is computed at run time. By definition sizeof(char) is 1; every other size is a multiple of it.

The operand of sizeof is generally not evaluated, only its type is examined. So sizeof(x++) does not increment x. This makes sizeof safe in macros and in expressions such as malloc(n * sizeof *p).

C
size_t bytes = sizeof(int);
size_t count = sizeof arr / sizeof arr[0];

Try it

C Sizes of types and objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C The expression is not evaluated; arrays decay in parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
sizeof expression
sizeof (type-name)
Form Description
sizeof expression Size of the expression's type. Parentheses are optional.
sizeof (type) Size of the type. Parentheses are required.

Returns: a value of type size_t (print it with %zu).

Errors: sizeof cannot be applied to a function type, an incomplete type (such as void or struct s; without a definition), or a bit-field.

Usage notes

  • Array length idiom: sizeof arr / sizeof arr[0] works only for real arrays, not for pointers or array parameters, which have been adjusted to pointers.
  • sizeof *p beats sizeof(type). If the type of p changes, the allocation follows automatically.
  • Structs include padding. sizeof(struct) is usually larger than the sum of the members; see padding.
  • Not a function. It is an operator, so sizeof x is valid. It binds tighter than * and /.
  • Unsigned result. Mixing sizeof with negative int values in a comparison converts the int to unsigned and surprises you.
  • Character constants have type int in C. sizeof 'a' equals sizeof(int) (4 here), unlike C++ where it is 1.
  • VLAs. The operand is evaluated if its type is a variable length array type.
  • C23 adds nothing new, but typeof pairs well: sizeof(typeof(x)).