C++ sizeof


A unary operator that yields the size in bytes of its operand, which may be either an expression or a type. If the operand is an expression, it is not evaluated. The size is a constant expression of type std::size_t.

If the operand is a type, it must be parenthesized.

  • It is illegal to apply sizeof to a function type.
  • It is illegal to apply sizeof to an incomplete type, including void.
  • If sizeof is applied to a reference type T& or T&&, it is equivalent to sizeof(T).
  • When sizeof is applied to a class type, it yields the number of bytes in a complete object of that type, including any padding bytes in the middle or at the end. Therefore, a sizeof expression can never have a value of 0. See layout of object types for more details.
  • The char, signed char, and unsigned char types have a size of 1. Conversely, a byte is defined to be the amount of memory required to store a char object. It does not necessarily mean 8 bits, as some systems have char objects longer than 8 bits.

If expr is an expression, sizeof(expr) is equivalent to sizeof(T) where T is the type of expr.

int a[100];
std::cout << "The number of bytes in `a` is: " << sizeof a;
memset(a, 0, sizeof a); // zeroes out the array

The sizeof... operator yields the number of elements in a parameter pack.

template <class... T>
void f(T&&...) {
    std::cout << "f was called with " << sizeof...(T) << " arguments\n";