Implement your own sizeof operator using C++


There is an option that we can implement our own sizeof() operator. The operator sizeof() is a unary operator and is used to calculate the size of any type of data. We can use #define directive to implement our own sizeof() operator which will work exactly same as sizeof() operator.

Here is the syntax to implement own sizeof() operator,

#define Any_name(object) (char *)(&object+1) - (char *)(&object)

Here,

Any_name − The name you want to give to your own sizeof() operator.

Here is an example to implement sizeof() operator in C language,

Example

 Live Demo

#include <stdio.h>
#define to_find_size(object) (char *)(&object+1) - (char *)(&object)
int main() {
   int x;
   char a[50];
   printf("Integer size : %d\n", to_find_size(x));
   printf("Character size : %d\n", to_find_size(a));
   return 0;
}

Output

Integer size : 4
Character size : 50

In the above program, #define directive is used to declare our own sizeof() operator and it is calculating the size of integer and character type array.

#define to_find_size(object) (char *)(&object+1) - (char *)(&object)
….
int x;
char a[50];
printf("Integer size : %d\n", to_find_size(x));
printf("Character size : %d\n", to_find_size(a));

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

544 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements