sizeof [C++ Reference]
Keywords: keywords,sizeof
Date: 2008-12-02T12:27:07-0800

[[sizeof]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- fr
- it
- jp
- pl
- ru
- tr

## sizeof

The sizeof operator is a compile-time operator that returns the size of the argument passed to it. The size is a multiple of the size of a char, which on many personal computers is 1 byte (or 8 bits). The number of bits in a char is stored in the CHAR_BIT constant defined in the <climits> header file. For example, the following code uses sizeof to display the sizes of a number of variables:

        struct EmployeeRecord {
          int ID;
          int age;
          double salary;
          EmployeeRecord* boss;
        };

        ...

        cout << "sizeof(int): " << sizeof(int) << endl
             << "sizeof(float): " << sizeof(float) << endl
             << "sizeof(double): " << sizeof(double) << endl
             << "sizeof(char): " << sizeof(char) << endl
             << "sizeof(EmployeeRecord): " << sizeof(EmployeeRecord) << endl;

        int i;
        float f;
        double d;
        char c;
        EmployeeRecord er;

        cout << "sizeof(i): " << sizeof(i) << endl
             << "sizeof(f): " << sizeof(f) << endl
             << "sizeof(d): " << sizeof(d) << endl
             << "sizeof(c): " << sizeof(c) << endl
             << "sizeof(er): " << sizeof(er) << endl;

On some machines, the above code displays this output:

        sizeof(int): 4
        sizeof(float): 4
        sizeof(double): 8
        sizeof(char): 1
        sizeof(EmployeeRecord): 20
        sizeof(i): 4
        sizeof(f): 4
        sizeof(d): 8
        sizeof(c): 1
        sizeof(er): 20

Note that sizeof can either take a variable type (such as int) or a variable name (such as i in the example above). It is also important to note that the sizes of various types of variables can change depending on what system you're on. Check out a_description_of_the_C_and C++_data types for more information. The parentheses around the argument are only required if you are using sizeof with a variable type (e.g. sizeof(int)). Parentheses can be left out if the argument is a variable or array (e.g. sizeof x, sizeof myArray).

Related Topics: C++_Data_Types

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •