C++ Programming/Programming Languages/C++/Code/Keywords/sizeof

The   keyword refers to an operator that works at compile time to report on the size of the storage occupied by a type of the argument passed to it (equivalently, by a variable of that type). That size is returned as 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 header file. This is one of the operators for which operator overloading is not allowed.

For example, the following code uses   to display the sizes of a number of variables:

On most machines (considering the size of char), the above code displays this output:

It is also important to note that the sizes of various types of variables can change depending on what system you're on. Check the data types page for more information.

Syntactically,   appears like a function call when taking the size of a type, but may be used without parentheses when taking the size of a variable type (e.g. ). Parentheses can be left out if the argument is a variable or array (e.g. ,  ). Style guidelines vary on whether using the latitude to omit parentheses in the latter case is desirable.

Consider the next example:

Since   does not evaluate anything at run time, the  function is never called. All information needed is the return type of the function, the first  will return the size of a short (the return type of the function) as the value 2 (in size_t, an integral type defined in the include file STDDEF.H) and the second   will return 4 (the size of size_t returned by the first  ).

  measures the size of an object in the simple sense of a contiguous area of storage; for types which include pointers to other storage, the indirect storage is not included in the value returned by  . A common mistake made by programming newcomers working with C++ is to try to use   to determine the length of a string; the std::strlen or std::string::length functions are more appropriate for that task.

  has also found new life in recent years in template meta programming, where the fact that it can turn types into numbers, albeit in a primitive manner, is often useful, given that the template metaprogramming environment typically does most of its calculations with types.