Home » sizeof() operator in C

sizeof() operator in C

by Online Tutorials Library

sizeof() operator in C

The sizeof() operator is commonly used in C. It determines the size of the expression or the data type specified in the number of char-sized storage units. The sizeof() operator contains a single operand which can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. The data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer data types and compound data types such as unions and structs.

Need of sizeof() operator

Mainly, programs know the storage size of the primitive data types. Though the storage size of the data type is constant, it varies when implemented in different platforms. For example, we dynamically allocate the array space by using sizeof() operator:

In the above example, we use the sizeof() operator, which is applied to the cast of type int. We use malloc() function to allocate the memory and returns the pointer which is pointing to this allocated memory. The memory space is equal to the number of bytes occupied by the int data type and multiplied by 10.

Note:
The output can vary on different machines such as on 32-bit operating system will show different output, and the 64-bit operating system will show the different outputs of the same data types.

The sizeof() operator behaves differently according to the type of the operand.

  • Operand is a data type
  • Operand is an expression

When operand is a data type.

In the above code, we are printing the size of different data types such as int, char, float with the help of sizeof() operator.

Output

sizeof() operator in C

When operand is an expression

In the above code, we have created two variables ‘i’ and ‘j’ of type double and float respectively, and then we print the size of the expression by using sizeof(i+j) operator.

Output

size of (i+j) expression is : 8  

You may also like