Writing own sizeof operator

This is a discussion on Writing own sizeof operator within the C Programming forums, part of the General Programming Boards category; How can I write my own sizeof operator? Any idea please?...

  1. #1
    Anirban Ghosh
    Join Date
    Jan 2006
    Posts
    278

    Writing own sizeof operator

    How can I write my own sizeof operator? Any idea please?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,401
    Why do you want to do this?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Anirban Ghosh
    Join Date
    Jan 2006
    Posts
    278
    No I was just asked but couldn't answer.
    Any idea please?

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,401
    I may be wrong, but I believe that it is impossible in standard C.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    I think the sizeof operator has a lot of support from the compiler and can operate at compile time so anything you build at runtime wouldn't have the same usage

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Why do you want to do this?
    "Find the size of an object without using the sizeof operator" is not an uncommon trivia question.

    >I may be wrong, but I believe that it is impossible in standard C.
    Duplicating the exact semantics of sizeof would require writing your own preprocessor. But if you reduce the problem to getting the size of an existing object rather than either a type name or an existing object, it's pretty easy:
    Code:
    #define SIZEOF(x) ((char*)(&(x) + 1) - (char*)&(x))
    Accepting a type name in any convenient way is harder because ultimately you would want to declare a temporary object and use the above solution.
    My best code is written with the delete key.

  7. #7
    Anirban Ghosh
    Join Date
    Jan 2006
    Posts
    278
    Quote Originally Posted by Prelude View Post
    >Why do you want to do this?
    "Find the size of an object without using the sizeof operator" is not an uncommon trivia question.

    >I may be wrong, but I believe that it is impossible in standard C.
    Duplicating the exact semantics of sizeof would require writing your own preprocessor. But if you reduce the problem to getting the size of an existing object rather than either a type name or an existing object, it's pretty easy:
    Code:
    #define SIZEOF(x) ((char*)(&(x) + 1) - (char*)&(x))
    Accepting a type name in any convenient way is harder because ultimately you would want to declare a temporary object and use the above solution.
    Okay so what does the above macro mean. I am confused. Could please throw some light.

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Okay so what does the above macro mean.
    Subtracting two pointers results in the number of items[1] between those pointers. If you cast the two pointers to char*, subtraction then results in the number of bytes between the two pointers[2]. With that in mind, the macro creates two pointers from the object: one to the object itself and one to the "next" object[3]. Those two pointers are cast to char*, because we want the number of bytes between them and not the number of objects (we already know the number of objects is 1). Finally, the two pointers to char are subtracted to get the difference between the addresses in bytes.


    [1] Where an item is an object of the pointed to type. So if p and q are pointers to int, p - q tells you how many objects of type int there are between those two addresses.

    [2] The char type is guaranteed to be one byte.

    [3] The "next" object doesn't really exist, but the address can still be calculated. Just don't dereference that pointer.
    My best code is written with the delete key.

  9. #9
    Registered User
    Join Date
    Sep 2008
    Posts
    200
    Quote Originally Posted by Prelude View Post
    >I may be wrong, but I believe that it is impossible in standard C.
    Duplicating the exact semantics of sizeof would require writing your own preprocessor.
    I don't know - I think this does the trick (only managed to work this out after seeing your SIZEOF macro, though...):

    Code:
    #include <stdio.h>
    
    #define SIZEOF(X)                            \
        ({                                       \
            __typeof__(X) x;                     \
            ((char *)(&x + 1) - (char *)&x);     \
        })
            
    
    int main(void)
    {
        struct s {
            int x;
            float p;
            int y;
        };
        printf("%d\n", SIZEOF(struct s));
        return 0;
    }

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >I don't know - I think this does the trick
    I'm sure it does...on your compiler. Keep in mind that my reply to laserlight was in reference to standard C. If you leave the realm of portability, anything is possible. The big problem with a sizeof macro in standard C is being able to create a temporary object and also use the macro as an expression (the paren wrapped compound statement you used is a compiler extension). If you change the semantics, it can be done easily:
    Code:
    #include <stdio.h>
    
    #define SIZEOF_T(X,result) { \
        X x; \
        result = (unsigned long)((char *)(&x + 1) - (char *)&x); \
    }
    
    int main(void)
    {
        struct s {
            int x;
            float p;
            int y;
        };
        unsigned long size;
    
        SIZEOF_T(struct s, size);
        printf("%lu\n", size);
    
        return 0;
    }
    But this solution may or may not be valid depending on the limitations of the question. Usually the question requires the macro to have as close to an equivalent syntax to the sizeof operator as possible.
    My best code is written with the delete key.

  11. #11
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by Prelude View Post
    >I don't know - I think this does the trick
    I'm sure it does...on your compiler. Keep in mind that my reply to laserlight was in reference to standard C. If you leave the realm of portability, anything is possible. The big problem with a sizeof macro in standard C is being able to create a temporary object and also use the macro as an expression (the paren wrapped compound statement you used is a compiler extension). If you change the semantics, it can be done easily:
    Code:
    #include <stdio.h>
    
    #define SIZEOF_T(X,result) { \
        X x; \
        result = (unsigned long)((char *)(&x + 1) - (char *)&x); \
    }
    
    int main(void)
    {
        struct s {
            int x;
            float p;
            int y;
        };
        unsigned long size;
    
        SIZEOF_T(struct s, size);
        printf("%lu\n", size);
    
        return 0;
    }
    But this solution may or may not be valid depending on the limitations of the question. Usually the question requires the macro to have as close to an equivalent syntax to the sizeof operator as possible.
    Why not something like:
    Code:
    #define SIZEOF_T(T) (unsigned long)((char*)(((T*)NULL) + 1) - (char*)NULL)
    Doesn't require a temporary object, at least...

  12. #12
    Registered User
    Join Date
    Sep 2008
    Posts
    200
    Quote Originally Posted by Prelude View Post
    the paren wrapped compound statement you used is a compiler extension
    I didn't realise that. Fair enough - in that case, here's one that works for types and objects with no temporaries and (I think) is completely portable. By that, I mean it compiles on my machine with tcc and gcc -Wall -Wextra -Werror -g -std=c99 -pedantic-errors.

    Code:
    #include <stdio.h>
    
    #define SIZEOF(X) ((int)(&(*(__typeof__(X) *)0) + 1))       
    
    int main(void)
    {
        struct s {
            int x;
            float p;
            int y;
        } S;
        
        printf("%d\n", SIZEOF(struct s));
        printf("%d\n", SIZEOF(S));
        return 0;
    }

  13. #13
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    I don't think __typeof__ is part of C89 nor C99.

  14. #14
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Why not something like: [using NULL as a temporary]
    Arithmetic on a null pointer isn't portable. Though to be fair, it'll probably work on the majority of systems.
    My best code is written with the delete key.

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,401
    Quote Originally Posted by Prelude
    "Find the size of an object without using the sizeof operator" is not an uncommon trivia question.
    Yeah, but it is a different question.

    Quote Originally Posted by Bayint Naung
    I don't think __typeof__ is part of C89 nor C99.
    Indeed, I cannot find anything with "typeof" in the text of C99.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sizeof operator implementation
    By munish.forum in forum C Programming
    Replies: 5
    Last Post: 01-24-2010, 01:14 PM
  2. Failure to overload operator delete
    By Elysia in forum C++ Programming
    Replies: 16
    Last Post: 07-10-2008, 01:23 PM
  3. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  4. C++ Operator Overloading help
    By Bartosz in forum C++ Programming
    Replies: 2
    Last Post: 08-17-2005, 12:55 PM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-06-2003, 11:51 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21