Sizeof Operator

The prefix unary operator sizeof returns an integer constant that represents the size of memory space (in bytes) used by its operand (determined by its type, with some exceptions).

The operator sizeof can take either a type identifier or an unary expression as an operand. You cannot use sizeof with expressions of function type, incomplete types, parenthesized names of such types, or with lvalue that designates a bit field object.

Sizeof Applied to Expression

If applied to expression, the size of an operand is determined without evaluating the expression (and therefore without side effects). The result of the operation will be the size of the type of the expression’s result.

Sizeof Applied to Type

If applied to a type identifier, sizeof returns the size of the specified type. The unit for type size is sizeof(char) which is equivalent to one byte. The operation sizeof(char) gives the result 1, whether char is signed or unsigned.

Thus:

sizeof(char)             /* returns 1 */
sizeof(int)              /* returns 2 */
sizeof(unsigned long)    /* returns 4 */
sizeof(float)            /* returns 4 */

When the operand is a non-parameter of array type, the result is the total number of bytes in the array (in other words, an array name is not converted to a pointer type):

int i, j, a[10];
...
j = sizeof(a[1]);  /* j = sizeof(int) = 2 */
i = sizeof(a);     /* i = 10*sizeof(int) = 20 */

/* To get the number of elements in an array: */
int num_elem = i/j;

If the operand is a parameter declared as array type or function type, sizeof gives the size of the pointer. When applied to structures and unions, sizeof gives the total number of bytes, including any padding. The operator sizeof cannot be applied to a function.

Copyright (c) 2002-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code