I saw the following weird type of macro in C (Linux) code here:
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))
What does ((t*)0)->f)
do?
How does it work?
I saw the following weird type of macro in C (Linux) code here:
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))
What does ((t*)0)->f)
do?
How does it work?
The thing does exactly what the name suggests – deliver the size of a field of a struct.
what it first does is cast 0 (which is an arbitrary address) to a pointer of the type of struct.
Then it ->
(access via pointer) takes the field and applies sizeof
to it.
Pretty straightforward!
It does what it says on the tin, like Marcus Müller explains. If you are wondering why bother with it, why can't we just do sizeof(type_of_field)
instead, then consider this:
struct foo {
struct {
int a;
float b;
} bar;
};
We cannot name type_of_bar
, since for the programmer it has no name. But the macro allows us to obtain the field size via a workaround, regardless.
Because sizeof is computed at compile time (except in the case of variable length arrays, which is not the case here) its argument is not evaluated at runtime. It is therefore OK to cast a NULL pointer, as it's only used to indicate the field for which size is being computed.