sizeof operator

Queries size of the object or type.

Used when actual size of the object must be known.

Syntax

sizeof( type ) (1)
sizeof expression (2)

Both versions return a constant of type std::size_t.

Explanation

1) returns size in bytes of the object representation of type.

2) returns size in bytes of the object representation of the type, that would be returned by expression, if evaluated.

Notes

Depending on the computer architecture, a byte may consist of 8 or more bits, the exact number being recorded in CHAR_BIT.

sizeof(char), sizeof(signed char), and sizeof(unsigned char) always return 1.

sizeof cannot be used with function types, incomplete types, or bit-field glvalues.

When applied to a reference type, the result is the size of the referenced type.

When applied to a class type, the result is the size of an object of that class plus any additional padding required to place such object in an array.

When applied to an empty class type, always returns 1.

When applied to an expression that designates a polymorphic object, the result is the size of the static type of the expression.

Keywords

sizeof.

Example

The example output corresponds to a system with 64-bit pointers and 32-bit int.

#include <iostream>
struct Empty {};
struct Base { int a; };
struct Derived : Base { int b; };
struct Bit {unsigned bit:1; };
int main()
{
    Empty e;
    Derived d;
    Base& b = d;
    Bit bit;
    std::cout << "size of empty class: "     << sizeof e        << '\n'
              << "size of pointer : "        << sizeof &e       << '\n'
//            << "size of function: "        << sizeof(void())  << '\n'  // compile error
//            << "size of incomplete type: " << sizeof(int[])   << '\n'  // compile error
//            << "size of bit field: "       << sizeof bit.bit  << '\n'  // compile error
              << "size of array of 10 int: " << sizeof(int[10]) << '\n'
              << "size of the Derived:     " << sizeof d << '\n'
              << "size of the Derived through Base: " << sizeof b << '\n';
 
}

Possible output:

size of empty class: 1
size of pointer : 8
size of array of 10 int: 40
size of the Derived:     8
size of the Derived through Base: 4

See also

C documentation for sizeof
doc_CPP
2016-10-11 10:00:03
Comments
Leave a Comment

Please login to continue.