I am wondering whether a simple macro offset_of_ requires a pointer dereference of not. For example, a C++ (means that this code will be compiled using a C++ compiler) struct which is declared with packed attribute
struct A {
int x;
int y;
} __attribute__(packed);
Suppose that sizeof(int) == 4 in this case, to calculate the offset of y inside A, I wrote a simple macro:
#define offset_of_y (ptrdiff_t)(&(((A*)0)->y))
Can we be sure that the value of this macro is always 4? Is there any pointer dereference from 0 (which may be a UB) when the macro is invoked?
Many thanks for any response.
Accessing something through a null pointer is UB, period.
(Unless the context is unevaluated, but in this case it IS evaluated.)
You probably want offsetof().
In practice your code probably could work, buf formally it's undefined.
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