Factory Design Pattern
October 23, 2012
Using sizeof to get size of an Array or pointer
November 6, 2012

sizeof operator in C/Cpp language

sizeof is a unique operator in C/C++ language which returns the amount of memory (in bytes) allocated to its operand. For example, if an implementation stores an integer in 2 bytes then both the statements below will output 2.

printf("%d", sizeof(int));
int x = 10;
printf("%d", sizeof x);

Note than sizeof operator is used like a function when applied on data types.

 sizeof(float)

Let’s understand some more facts about sizeof operator:

1. Operator and not a function

First thing to note about sizeof is that it is an operator and not a function, even if we write it like a function.

sizeof(int); // looks like a function but is an operator.

2. Applied at compile time

sizeof is the only operator which is applied at compile time. For example: if your code has a statement like

int x = sizeof(double);

the the compiler will replace it with (assuming that double is stored in 8 bytes)

int x = 8;

This is to make the processing fast, because the information about which data type is allocated how much memory is available at the compiler.

Note: If your program is compiled at one machine environment then it may behave differently in some other environment (where sizeof(double) is different).

Note: In C99, you may define variable length arrays. If sizeof is applied on a variable length array, then it will be execution time (and NOT compile time).

3. Can be applied on complete types.

If the definition of a variable or type is not complete, then sizeof operator cannot be applied on it. For example: If a struct is defined in some other file and is declared in this file (using extern), then sizeof cannot be applied on that struct in the file where it is declared.

extern struct Node;
sizeof(Node); //ERROR.. cannot apply on incomplete type

4. sizeof on struct

In C/C++ the actual memory allocated to a struct may be more than the sum of size of its individual fields. This is because some compilers tend to align individual fields of struct to word boundaries, hence leave holes (empty memory) between two fields of struct. Also see this post for more details.

struct ABC{
  char a; // 1 byte
  int b; // 2 bytes
};
printf("%zu", sizeof(struct ABC));

The output may not be 3. (Note that the actual size of int is machine dependent).

5. Return value is of type size_t

The return type of sizeof operator is size_t. It is nothing but usually another name for unsigned int.

size_t a = sizeof(int);

Leave a Reply

Your email address will not be published. Required fields are marked *