Skip to main content
gamedev.net
🔒 Locked

C/C++ macro question

Started by Solburn 4 replies 200+ views
Original Post
Solburn
Solburn
What would a macro (in C/C++) like this do and what would it be used for? #define test(z, w) (int)(&(((z *)0)->w)) This is what I think so far: This takes 2 parameters, z being an instance of some class/struct (lets say foo), w being a member of foo. 1. If z is intended to be a type name of struct foo, the (z*)0 -> w would become (foo *)0 -> w allowing the type checker to access the w field in foo. 2. The data member''s address or it''s struct''s pointer address is set to 0 (maybe?) 3. The address of the data member ''w'' is then converted to an int Can someone tell me exactly how this works and maybe what it''s purpose is? I have a feeling it is either pushing the data member''s address to the top of the stack or creating a null pointer out of it...I am not sure.
mutex
mutex
Looks like it''s taking the address of a class function. Or maybe the offset of a variable from the beginning of the class?

Extrarius
Extrarius
It returns the offset of a member of a class/struct from the address of a class. For ex, if test(foo, location) returned 4, that means that &(a.location) is &a+4 if a is of type foo.

----------
Almost typo-ified using Extrarius'' AUTOMATIC Typo Generator, but I decided to be nice =-)
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
Solburn
Solburn
quote:
Original post by Extrarius
It returns the offset of a member of a class/struct from the address of a class. For ex, if test(foo, location) returned 4, that means that &(a.location) is &a+4 if a is of type foo.



So using this macro could be useful in finding how much memory is between a data member and an instance of its parent class/struct?

[edited by - solburn on February 24, 2003 10:43:45 PM]
risingdragon3
risingdragon3
Indeed, it finds out the address for a POD (plain old data type) of a offset of a member. (A POD = no virtual functions, no base classes).
Yes, you can use it to access a member in a structure without actually knowing the name of the member or the type of the struct (in C). (No type safety...you better know what you''re doing!)
You can use member pointers in C++ to do similar things in C++. Then it works w/ non-POD types.

I just recently used it to implement a compile-time property / reflection system.

*500

-----------------------------
Gamedev for learning.
libGDN for putting it all together.
Null and Void
Null and Void
There is a standard macro that does the same thing as that macro anyway: offsetof in stddef.h (as well as cstddef in C++). The name ''offsetof'' makes it pretty obvious what it does (as they''ve already explained: the offset of the member variable from the from of the struct/class).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.