Implement Your Own sizeof Operator Using C++



In C++, the sizeof() operator is a unary operator which is used to calculate the size of any data type.

Implementing sizeof() Operator

We can use the #define directive to implement a macro that copies the behavior of the sizeof() operator for objects, though it will not be the same as the sizeof() operator.

Syntax

Following is the syntax of C++ macro to implement the sizeof():

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

Here,

  • any_name : The name you want to give to your own sizeof() operator.

Note: The main benefit of using MACROS is defining by once and using them multiple times which saves the time and repetition of code.

Example to Implement Own Sizeof() Operator

In this example, we create two variables say int and char and assign the respective values. Then these variables passes to the macros to generate the result of own sizeof() operator:

#include <iostream>
// defining macros
#define to_find_size(object) (char *)(&object + 1) - (char *)(&object)
using namespace std;

int main() {
   // declare the variable
   int x;
   char a[50];

   // display the result
   cout << "Integer size : " << to_find_size(x) << endl;
   cout << "Character array size : " << to_find_size(a) << endl;

   return 0;
}

Output

The above program produces the following result:

Integer size : 4
Character size : 50

Therefore, this way we can implement our own sizeof() operator.

Updated on: 2025-04-21T18:00:20+05:30

857 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements