sizeof operator - Implementing it !!

Aug 13, 2007 15 Replies

Hi,



How could i implement my own 'sizeof' operator ?



Thx in advans, Karthik Balaguru



You can't, it's a compiler built-in. Only the compiler knows how big it's going to make something.

Is this homework? Last hundred times it was asked, it really was homework... Please, search comp.lang.c or comp.lang.c++ to take a look at the responses given

Regards

I think the code following code will works :-)

#include

void *var_name = NULL;

#define MY_SIZEOF(var) ( \ (unsigned long)((char *)(++((var *)var_name))) \ )

int main(void) { printf("%d\n",MY_SIZEOF(char *)); return 0; }

Hi,

Thx for your replies. I did search the net and got some cool info :):)

Interesting stuff to share with you : #define sizeof(X) ((char *) &((X)+1) - (char *) &(X))

I think this method looks coooooooool :):)

Refer the link

formatting link

Thx in advans, Karthik Balaguru

link

formatting link

#include

void *var_name = NULL;

#define MY_SIZEOF(var) ( \ (var_name = NULL, (unsigned long)((char *)(++((var

*)var_name)))) \ )

int main(void) { printf("%d\n",MY_SIZEOF(char *)); return 0;

}

That's not even close.

You can't. Nor would there be any point in trying.

It doesn't. For starters, the name of the macro argument is nastily misleading.

Your Implementation is pretty good, but it can't take the argument like: int *, char *, int...etc.

Bzzzt. That's not executable code. It's a hack to get the compiler to tell you what it's already prepared to tell you using the sizeof operator. There is no executable code that can perform a sizeof operator in standard C.

You can't, because its results depend on system conditions. That's why it is a standard operator in C, i.e. the C implementor does it for the system on which it runs.

Chuck F (cbfalconer at maineline dot net) Available for consulting/temporary embedded and systems.

On Mon, 13 Aug 2007 00:22:38 -0700, Dibyendu wrote in comp.arch.embedded:

Incrementing a null pointer, or applying any arithmetic operation on it at all, is undefined behavior. Period.

Jack Klein Home: http://JK-Technology.Com FAQs for comp.lang.c http://c-faq.com/ comp.lang.c++ http://www.parashift.com/c++-faq-lite/alt.comp.lang.learn.c-c++ http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html

And if the code works, it isn't an implementation of sizeof -- it's a backhanded way of getting the compiler to use the built-in sizeof operator that is already there.

#define my_sizeof(x) sizeof(x)

David M. Palmer dmpalmer@email.com (formerly @clark.net, @ematic.com)

Exactly. The same trick is widely used to implement offset_of, which doesn't have an alternate, BTW, and can be quite useful if you're that kind of (ab)user :-).

Join the Discussion

Have something to add? Share your thoughts — no account required.

Didn't find your answer?

Ask the community — no account required