C program to implement your own sizeof operator

  • Write a program in C to implement your own sizeof operator macro.

Required knowledge: sizeof operator.

The sizeof is a compile time operator not a standard library function. The sizeof is a unary operator which returns the size of passed variable or data type in bytes. As we know, that size of basic data types in C is system dependent, hence we use sizeof operator to dynamically determine the size of variable at run time.

Algorithm to implement your own sizeof operator.
Here we are going to do a pointer arithmetic trick to get the size of a variable. Here is the generic approach to find size of any variable without using sizeof operator:
  • Suppose we want to find the size of variable 'Var' of data type D(for example an integer variable 'Var').
  • Get the base address of the variable 'Var' using address of(&) operator.
  • When we increment a pointer variable, it jumps K bytes ahead where K is equal to the size of the variable's data type.
  • Now, ((&Var + 1) - &Var) will give the size of the variable Var of data type D.

C program to implement you own sizeof operator

#include <stdio.h>

#define new_sizeof(var) (char *)(&var+1) - (char *)(&var)

int main() {
    int i;
    double f;

    printf("Integer size from sizeof : %d bytes\n", sizeof(i));
    printf("Integer size from my_sizeof : %d bytes\n", new_sizeof(i));
    printf("Float size from sizeof : %d bytes\n", sizeof(f));
    printf("Float size from my_sizeof : %d bytes\n", new_sizeof(f));
    return 0;
}
Output
Integer size from sizeof : 4 bytes
Integer size from my_sizeof : 4 bytes
Float size from sizeof : 8 bytes
Float size from my_sizeof : 8 bytes