English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Using C ++Implement your own sizeof operator

We can choose to implement our ownsizeof()operator. This operatorsizeof()It is a unary operator used to calculate the size of any data type. We can use the #define directive to implement our ownsizeof()operator, which will besizeof()operator completely.

This is the same as implementing your ownsizeof()The syntax of the operator,

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

Here,

Any_name-Do you want to name yoursizeof()The name of the operator.

This issizeof()Example of implementing an operator in C language

Example

#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 result

Integer size: 4
Character size: 50

In the above program, the #define directive is used to declare our ownsizeof()Operator, which is calculating the size of integer and character type arrays.

#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));