The Cult AGP

here is the code which uses a simple macros to implement the sizeof operator

using namespace std;
#define getsize(x) ((char *)(&(x) + 1) – (char *)&(x)) //macros
char a[]=”hello”;
cout<<getsize(a); //output is 6 because backslash 0 has to be considered.

return 0;

Comments on: "Sizeof operator implementation" (11)

  1. Not bad, but what does it do for «getsize(7)» and «getsize(“foo”)» and how does that compare with the real sizeof?

  2. hey..
    you can write int a=7;
    then getsize(a) returns 4 as the value..
    same logic for “foo”;

    the concept here is using the difference in the memory locations allocated for a particular data structure.

  3. Hi,

    Could plz elaborate how ur macro works????

  4. I just want to why you type casted to “char*” only.

  5. the macros is a simple pointer based manipulation,we use in order to achieve the desired result..

  6. What about getsize(int)?

  7. please refer to comment no : 2

  8. It will work this way
    #define size1(var) (void *)(&var+1)-(void *)(&var) //for variable
    #define size2(type) ((void *)((type *)(1)+1))-((void *)((type *)(1))) //for datatype

  9. Hey i know this is a very late comment..
    But as per your implementation what happens in this case is :


    This expands to :
    ((char *)(&(int) + 1) – (char *)&(int))
    which is not legal. Hence it will throw an error.

  10. Right, this won’t work for data types.

    Though, refer to Srikant’s solution “size2”.
    With a minor correction of replacing void with char it will work fine. (pointer arithmetic can’t be done on void pointers).

    so for data types –
    #define misizeof(type) ((char*)((type*)(1)+1)-(char*)(type*)(1))

  11. Yeah…and if sizeof is to be implemented in a generic way, i think that can be done only in a compiler. Because compiler is the one who does symbol resolution…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: