I came across the macro below
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
I kind of not able to digest this because in c++, when I try to deference a null pointer, I expect an unexpected behaviour... but how come it can have an address? what does address of null mean?
For the purpose of the macro:
It assumes that there is an object of type TYPE
at address 0 and returns the address of the member which is effectively the offset of the member in the structure.
This answer explains why this is undefined behaviour. I think that this is the most important quote:
If
E1
has the type “pointer to class X,” then the expressionE1->E2
is converted to the equivalent form(*(E1)).E2
;*(E1)
will result in undefined behavior with a strict interpretation, and.E2
converts it to an rvalue, making it undefined behavior for the weak interpretation.
which is the case here. Although others think that this is valid. It is important to note that this will produce the correct result on many compilers though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With