Dheeraj
Dheeraj

Reputation: 69

How to write custom sizeof() function in c?

I want to implement an alternative custom function for c sizeof() operator. I got below definition from internet and its working pretty good.

#define my_sizeof(type) (char *)(&type+1)-(char*)(&type)

But instead of preprocessor (#define macro) function i would like to implement it as a separate function as below. Can somebody help me to complete the definition of sizeof_custom()?

Note: Why I wanted to implement in this way is to understand cause of the difficulties I faced while I try to implement it with void pointers and find the diff (I understand void pointer does not allow arithmetic operations, but then how I can build this function?). Please help.

#include <stdio.h>

return_type sizeof_custom ( arg )
{
....
....
// return the size of the variable
}

void main() 
{
int a;  // It can be int, float, char,....
printf("size = %d", sizeof_custom(a));
}

Upvotes: 0

Views: 490

Answers (1)

KamilCuk
KamilCuk

Reputation: 142005

It's not possible to implement sizeof operator using other language features. It is part of the language and has to be implemented by the compiler. Most importantly because:

  • array types do not decay to pointers
  • expression in sizeof is not evaluated
  • variable-length arrays are handled specially

Upvotes: 3

Related Questions