C/89 doesn't have it and in Linux you have to "emulate" it by this
#define field_sizeof(t, f) (sizeof(((t*)0)->f))
In the C23 standard, however, footnote 4 explicitly states that
(void *)0 is valid in the operand of
alignas,
alignof, and
sizeof expressions. Thus, in C23,
#define field_sizeof(type, member) (sizeof ((type *)0)->member)can be understood/accepted as being valid (as long as
member is not a variable length array at least).
There are also quite a few userspace users of that, and in definitions of the related
offsetof macro,
#define offsetof(type, member) ((size_t) &(((type *)0)->member))so any compiler that cannot handle these will fail to compile quite lot of existing C code, too.
(It is important to remember that aside from C11, the C standard has evolved by including stuff compilers have implemented and users use; not by defining or dictating completely new features not implemented yet by any compiler.)
My opinion: this topic is informative, the field_sizeof() operator should be built-in in every C/C-like compiler!
Agreed.
GCC has traditionally implemented many related operators as an extension to C:
- __alignof__, standardized in C11 as _Alignof and in C23 as alignof
- __alignas__, standardized in C11 as _Alignas and in C23 as alignas
- typeof, standardized in C23 as typeof (and typeof_unqual for the non-atomic unqualified type of the expression)
which are similarly useful.
typeof and compound statements in parentheses (another GCC extension) allow macros that only evaluate their parameters only once (as long as they are not variably modified types):
#define foo(x, y) ({ typeof (x) _x = (x); typeof (y) _y = (y); use _x and _y ... ; result; })