sizeof operator

From cppreference.com
 
 
C++ language
General topics
Preprocessor
Comments
Keywords
ASCII chart
Escape sequences
History of C++
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

Queries size of the object or type

Used when actual size of the object must be known

Contents

[edit] Syntax

sizeof( type )
sizeof expression

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

[edit] 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.

[edit] Notes

sizeof(char), sizeof(signed char), and sizeof(unsigned char) always return 1, regardless of the value of CHAR_BIT.

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

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.

[edit] Keywords

sizeof

[edit] Example

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

#include <iostream>
struct Empty {};
struct Bit {unsigned bit:1; };
int main()
{
    Empty e;
    Bit b;
    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 b.bit    << '\n'  // compile error
              << "size of array of 10 int: " << sizeof(int[10]) << '\n';
}

Output:

size of empty class: 1
size of pointer : 8
size of array of 10 int: 40

[edit] See also