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).
size_t bytes = sizeof(int); size_t count = sizeof arr / sizeof arr[0];
Try it
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.
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
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 *pbeatssizeof(type). If the type ofpchanges, 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 xis valid. It binds tighter than*and/. - Unsigned result. Mixing
sizeofwith negativeintvalues in a comparison converts theintto unsigned and surprises you. - Character constants have type
intin C.sizeof 'a'equalssizeof(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
typeofpairs well:sizeof(typeof(x)).
Related
alignof,size_t, structure padding, VLAs- Lessons: Data types, Padding and alignment