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?
Because:
Rowsizeof expressionthe expression is not evaluated. It is in an "unevaluated context". Dereferencing aNULLpointer causes undefined behavior, but since this expression is not evaluated, theNULLpointer is not actually dereferenced and it's therefore safe.You could use a similar construct, pretending to actually create a
Struct:Again, since the expression after
sizeofis not evaluated, it doesn't actually create aStruct.