There is this macro offsetof in C/C++ which allows you to get the address offset of a member in a POD structure. For an example from the C FAQ:
struct foo {
int a;
int b;
};
struct foo;
/* Set the b member of foo indirectly */
*(int *)((char *)foo + offsetof(b)) = 0xDEADBEEF;
Now this just seems evil to me and I can't see many legit uses of this macro.
One legit example I have seen is it's use in the container_of macro in the Linux Kernel for getting the address of an embedded structures parent object:
/* get the address of the cmos device struct in which the cdev
structure which inode points to is embedded */
struct cmos_dev *cmos_devp =
container_of(inode->i_cdev, struct cmos_dev, cdev);
What other legit uses are there for this macro? When should you not use this macro?
EDIT So far this answer to a different SO question is the best one I've seen so far.
The offsetof() macro returns the offset of the element name within the struct or union composite. This provides a portable method to determine the offset. At this point, your eyes start to glaze over, and you move on to something that's more understandable and useful.
The C library macro offsetof(type, member-designator) results in a constant integer of type size_t which is the offset in bytes of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type.
Use offsetof() to find the offset from the start of z or from the start of x . #include <stddef. h> size_t offsetof(type, member); offsetof() returns the offset of the field member from the start of the structure type.
One of the ways I've used it in embedded systems is where I have a struct which represents the layout of non-volatile memory (e.g. EEPROM), but where I don't want to actually create an instance of this struct in RAM. You can use various nice macro tricks to allow you to read and write specific fields from the EEPROM, where offsetof does the work of calculating the address of a field within the struct.
With regard to 'evil', you have to remember that lots of stuff which was traditionally done in 'C' programming, particularly on resource-limited platforms, now looks like evil hackery when viewed from the luxurious surrounding of modern computing.
One legitimate use of offsetof()
is to determine the alignment of a type:
#define ALIGNMENT_OF( t ) offsetof( struct { char x; t test; }, test )
It may be a bit low-level to need the alignment of an object, but in any case I'd consider this a legitimate use.
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