The sizeof
operator in C is commonly used to determine the size of an expression or data types. It is a compile-time unary operator that returns the size of the memory allocated to that data type.
sizeof
operator is not used with primitive data types but can also be used with the pointer data type, union, struct, etc.
Note: Although, the output varies with the Machine that is 32-bit system and 64-bit system can show different values for same data types.
Its use in program:
The sizeof
operator behaves differently depending on the operand type:
- When the operand is a Data Type
- When the operand is an expression
1. When the operand is a Data Type
When used with data types such as integer, float, etc. It simply returns the amount of memory allocated to that data type.
Let us see an example in C to find the size of int, float, double and char variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include<stdio.h> int main() { int intVar; float floatVar; double doubleVar; char charVar; //size of each variables printf("Size of the Variables in bytes:\n"); printf("int: %zu\n", sizeof(intVar)); printf("float: %zu\n", sizeof(floatVar)); printf("double: %zu\n", sizeof(doubleVar)); printf("char: %zu\n", sizeof(charVar)); return 0; } |
Output:
1 2 3 4 5 | Size of the Variables in bytes: int: 4 float: 4 double: 8 char: 1 |
2. When the operand is an expression
When used with expression in a program, it returns the size of an expression. Let us see an example in C to find the size of an expression.
1 2 3 4 5 6 7 8 9 10 11 12 | #include <stdio.h> int main() { int a = 0; double d = 10.21; printf("Size of an expression (a+d): %d\n",sizeof(a+d)); int result = (int)(a+d); printf("Size of an explicitly converted expression: %d\n",sizeof(result)); return 0; } |
Output:
1 2 | Size of an expression (a+d): 8 Size of explicitly converted expression: 4 |