Sizeof operator in C

CProgrammingServer Side Programming

The sizeof operator is the most common operator in C. It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable. It can be applied to any data type, float type, pointer type variables.

When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type. The output can be different on different machines like a 32-bit system can show different output while a 64-bit system can show different of same data types.

Here is an example in C language,

Example

 Live Demo

#include <stdio.h>
int main() {
int a = 16;
   printf("Size of variable a : %d\n",sizeof(a));
   printf("Size of int data type : %d\n",sizeof(int));
   printf("Size of char data type : %d\n",sizeof(char));
   printf("Size of float data type : %d\n",sizeof(float));
   printf("Size of double data type : %d\n",sizeof(double));
   return 0;
}

Output

Size of variable a : 4
Size of int data type : 4
Size of char data type : 1
Size of float data type : 4
Size of double data type : 8

When the sizeof() is used with an expression, it returns the size of the expression. Here is an example.

Example

 Live Demo

#include <stdio.h>
int main() {
   char a = 'S';
   double b = 4.65;
   printf("Size of variable a : %d\n",sizeof(a));
   printf("Size of an expression : %d\n",sizeof(a+b));
   int s = (int)(a+b);
   printf("Size of explicitly converted expression : %d\n",sizeof(s));
   return 0;
}

Output

Size of variable a : 1
Size of an expression : 8
Size of explicitly converted expression : 4
raja
Published on 05-Oct-2018 17:06:54
Advertisements