F
Fred Zwarts
Consider the following definition:
typedef struct {
int a;
int b[100];
} s;
Now I have a function
void f (int i) { ... }
which needs to calculate the offset within s of b.
I used to use the offsetof macro for this purpose:
offsetof (s, b)
For most compiler environments offsetof is defined as a macro as follows
in stddef.h:
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
and in these cases my function works as I expected..
However, I now have a new compiler which uses a built-in function instead of this macro.
A error message is generated at compile time for my use of offsetof because
this built-in function requires that the second parameter of offsetof is a
compile-time constant. (I understand that there is some discussion about
the exact wording and interpretation of the standard with respect to the
constant requirement for offsetof.)
I have two questions, a theoretical and a practical one.
Why does the standard impose this limitation to offsetof?
It seems that there is a need to compute offsets that are not compile-time constants.
What is the best way to replace offsetof (s, b) in such a way that the result is
defined according to the C++ standard?
I understand that the result of the usual macro is not really defined because
a) address 0 does not necessarily have the value 0 and
b) type casting an address to size_t is not necessary well defined in all environments.
Regards,
Fred.Zwarts.
typedef struct {
int a;
int b[100];
} s;
Now I have a function
void f (int i) { ... }
which needs to calculate the offset within s of b.
I used to use the offsetof macro for this purpose:
offsetof (s, b)
For most compiler environments offsetof is defined as a macro as follows
in stddef.h:
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
and in these cases my function works as I expected..
However, I now have a new compiler which uses a built-in function instead of this macro.
A error message is generated at compile time for my use of offsetof because
this built-in function requires that the second parameter of offsetof is a
compile-time constant. (I understand that there is some discussion about
the exact wording and interpretation of the standard with respect to the
constant requirement for offsetof.)
I have two questions, a theoretical and a practical one.
Why does the standard impose this limitation to offsetof?
It seems that there is a need to compute offsets that are not compile-time constants.
What is the best way to replace offsetof (s, b) in such a way that the result is
defined according to the C++ standard?
I understand that the result of the usual macro is not really defined because
a) address 0 does not necessarily have the value 0 and
b) type casting an address to size_t is not necessary well defined in all environments.
Regards,
Fred.Zwarts.