This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: implementation of sizeof and typeof operator
- From: Jeff Epler <jepler at unpythonic dot net>
- To: vikaspushkar <vikaskupushkar at gmail dot com>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Fri, 14 Nov 2014 12:02:33 -0600
- Subject: Re: implementation of sizeof and typeof operator
- Authentication-results: sourceware.org; auth=none
- References: <1415814969323-1089232 dot post at n5 dot nabble dot com>
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