Reputation: 638
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.
Upvotes: 4
Views: 193
Reputation: 96013
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.
Upvotes: 4