ArticleslgStudy

science

Sizeof

Sizeof is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Sizeof rather than just read about it. In short: sizeof is a unary operator in the C and C++ programming languages that evaluates to the storage size of an expression or a data type, measured in units sized as char. Consequently, the expression sizeof(char) evaluates to 1.

Key takeaways

  • Sizeof belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Sizeof to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Sizeof from memory before moving on to harder problems.

Reference excerpt

sizeof is a unary operator in the C and C++ programming languages that evaluates to the storage size of an expression or a data type, measured in units sized as char. Consequently, the expression sizeof(char) evaluates to 1. The number of bits of type char is specified by the preprocessor macro CHAR_BIT, defined in the standard include file <limits.h>. On most modern computing platforms this is eight bits. The result of sizeof is an unsigned integer that is usually typed as size_t. The operator accepts a single operand which is either a data type expressed as a cast – the name of a data type enclosed in parentheses – or a non-type expression for which parentheses are not required.

Purpose Many programs must know the storage size of a particular datatype. Though for any given implementation of C or C++ the size of a particular datatype is constant, the sizes of even primitive types in C and C++ may be defined differently for different platforms of implementation. For example, runtime allocation of array space may use the following code, in which the sizeof operator is applied to the cast of the type int:

In this example, the malloc() function allocates memory and returns a pointer to the memory block. The size of the block allocated is equal to the number of bytes for a single object of type int multiplied by 10, providing space for ten integers. It is generally not safe to assume the size of any datatype. For example, even though most implementations of C and C++ on 32-bit systems define type int to be four octets, this size may change when code is ported to a different system, breaking the code. The exception to this is the data type char, which always has the size 1 in any standards-compliant C implementation. In addition, it is frequently difficult to predict the sizes of compound datatypes such as a struct or union, due to padding. The use of sizeof enhances readability, since it avoids unnamed numeric constants (magic numbers). An equivalent syntax for allocating the same array space results from using the dereferenced form of the pointer to the storage address, this time applying the operator to a pointer variable:

Use The operator sizeof produces the required memory storage space of its operand when the code is compiled. The operand is written following the keyword sizeof and may be the symbol of a storage space, e.g., a variable, an expression, or a type name. Parentheses for the operand are optional, except when specifying a type name. The result of the operator is the size of the operand in bytes, or the size of the memory storage requirement. For expressions, it evaluates to the representation size for the type that would result from evaluation of the expression, which is not performed. For example, since sizeof(char) is defined to be 1 and assuming the integer type is four bytes long, the following code fragment prints 1,4:

Certain standard header files, such as <stddef.h>, define size_t to denote the unsigned integral type of the result of a sizeof expression. The printf() width specifier z is intended to format that type. sizeof cannot be used in C preprocessor expressions, such as #if, because it is an element of the programming language, not of the preprocessor syntax or its macros, which have no data types. The following example in C++ uses the operator sizeof with variadic templates.

sizeof can be used with variadic templates in C++11 and above on a parameter pack to determine the number of arguments.

Application to arrays When sizeof is applied to the name of an array, the result is the number of bytes required to store the entire array. This is one of the few exceptions to the rule that the name of an array is converted to a pointer to the first element of the array, and is possible just because the actual array size is fixed and known at compile time, when the sizeof operator is evaluated. The following program uses sizeof to determine the size of a declared array, avoiding a buffer overflow when copying characters:

Here, sizeof buffer is equivalent to 10 * sizeof buffer[0], which evaluates to 10, because the size of the type char is defined as 1. C99 adds support for flexible array members to structures. This form of array declaration is allowed as the last element in structures only, and differs from normal arrays in that no length is specified to the compiler. For a structure named s containing a flexible array member named a, sizeof s is therefore equivalent to offsetof(s, a):

In this case the sizeof operator returns the size of the structure, including any padding, but without any storage allowed for the array. Most platforms produce the following output:

sizeof(FlexibleArray) == 4 C99 also allows variable length arrays that have the length specified at runtime, although the feature is considered an optional implementation in later versions of the C standard. In such cases, the sizeof operator is evaluated in part at runtime to determine the storage occupied by the array.

sizeof can be used to determine the number of elements in an array, by dividing the size of the entire array by the size of a single element. This should be used with caution; When passing an array to another function, it will "decay" to a pointer type. At this point, sizeof will return the size of the pointer, not the total size of the array. As an example with a proper array:

Incomplete types sizeof can only be applied to "completely" defined types. With arrays, this means that the dimensions of the array must be present in its declaration, and that the type of the elements must be completely defined. For structs and unions, this means that there must be a member list of completely defined types. For example, consider the following two source files:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Sizeof

Start with the simplest possible case. Write down what Sizeof claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Sizeof before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Sizeof ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Sizeof

In research
Sizeof appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Sizeof in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Sizeof is common in secondary-school and first-year university syllabi. It links to neighbouring topics C++, C (programming language), Operators (programming), so understanding it makes those chapters shorter.
In everyday life
Look for Sizeof outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Sizeof in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Sizeof means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Sizeof out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Sizeof in simple terms?

sizeof is a unary operator in the C and C++ programming languages that evaluates to the storage size of an expression or a data type, measured in units sized as char. Consequently, the expression sizeof(char) evaluates to 1.

Why does Sizeof matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Sizeof?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Sizeof.

Tags

  • C++
  • C (programming language)
  • Operators (programming)
  • Unary operations

Keep exploring