I have a struct named Row :
typedef struct
{
uint32_t id;
char username[COLUMN_USERNAME_SIZE];
char email[COLUMN_EMAIL_SIZE];
} Row;
Also, I have defined a Macro :
#define size_of_attribute(Struct, Attribute) sizeof(((Struct *)0)->Attribute)
// size of each attributes
const uint32_t ID_SIZE = size_of_attribute(Row, id);
const uint32_t USERNAME_SIZE = size_of_attribute(Row, username);
const uint32_t EMAIL_SIZE = size_of_attribute(Row, email);
Why are we using a null pointer while defining the size_of_attribute Macro to get the size of each data type in the struct Row? Is there any other way to express the above Macro?
Why are we using a null pointer while defining the size_of_attribute Macro to get the size of each data type in the struct Row?
Because:
Row
sizeof expression
the expression is not evaluated. It is in an "unevaluated context". Dereferencing a NULL
pointer causes undefined behavior, but since this expression is not evaluated, the NULL
pointer is not actually dereferenced and it's therefore safe.Is there any other way to express the above Macro?
You could use a similar construct, pretending to actually create a Struct
:
#define size_of_attribute(Struct, Attribute) (sizeof (Struct){}.Attribute)
Again, since the expression after sizeof
is not evaluated, it doesn't actually create a Struct
.