C Programming sizeof operator



In the previous chapter we have learnt about the assignment operator in C programming. In this chapter we will be learning sizeof operator.

C Programming sizeof operator

  1. sizeof operator is used to calcualte the size of data type or variables.
  2. sizeof operator can be nested.
  3. sizeof operator will return the size in integer format.
  4. sizeof operator syntax looks more like a function but it is considered as an operator in c programming

Example of sizeof() operator

Size of Variables

#include<stdio.h>

int main() {

   int ivar = 100;
   char cvar = 'a';
   float fvar = 10.10;

   printf("%d", sizeof(ivar));
   printf("%d", sizeof(cvar));
   printf("%d", sizeof(fvar));
   return 0;
}

Output :

214

In the above example we have passed a variable to sizeof operator. It will print the value of variable using sizeof() operator.

Size of Data Type

#include<stdio.h>

int main() {

   printf("%d", sizeof(int));
   printf("%d", sizeof(char));
   printf("%d", sizeof(float));
   
   return 0;
}

We will again get same output as that of above program. In this case we have directly passed an data type to an sizeof.

Size of constant

#include<stdio.h>

int main() {

   printf("%d", sizeof(10));
   printf("%d", sizeof('A'));
   printf("%d", sizeof(10.10));
   
   return 0;
}

In this example we have passed the constant value to a sizeof operator. In this case sizeof will print the size required by variable used to store the passed value.

Nested sizeof operator

#include<stdio.h>

int main() {
   int num = 10;
   printf("%d", sizeof(num));
   return 0;
}

We can use nested sizeof in c programming. Inner sizeof will be executed in normal fashion and the result of inner sizeof will be passed as input to outer sizeof operator.

Innermost Sizeof operator will evaluate size of Variable “num” i.e 2 bytes Outer Sizeof will evaluate Size of constant “2” .i.e 2 bytes