This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: implementation of sizeof and typeof operator


I don't think it's possible to implement 'sizeof' or 'typeof' in terms
of portable C constructs only.

If the thing for which the size is required is a type, then the
following nonportable construct works on a wide range of systems:
    #define sizeof_type(T) ((size_t)(((T*)0)+1))
    ...
    assert(sizeof(int) == sizeof_type(int));
    ...
(it is nonportable because the pointer arithmetic invokes undefined
behavior in C/C++)

to work on a type *or* a value, as C's sizeof() does, you'd need a way
to write
    (expression_is_a_type(X) ? sizeof_type(X) : sizeof_type(decltype(X)))
except there's no way to write expression_is_a_type in C, and it also
relies on C++11 decltype (similar to typeof, but at least it's a part of
a language standard)

In C++ it is possible to get some way to implementing 'typeof' using
templates.  e.g.,
http://www.drdobbs.com/a-portable-typeof-operator/184401310
http://stackoverflow.com/questions/12199280/how-to-implement-boost-typeof
but all these implementations are hacks which are ultimately
unsatisfactory, which is why decltype was added to C++11.

Jeff


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]