|
-
February 23rd, 2003, 04:23 AM
#1
Macro question
I'm in the middle of dissecting a program, and I've run across a weird macro... I can't seem to figure out what it does:
MACRO (z,w) ( (int) ( &(((z*)0)->w) )
I think w is a member variable of a class or structure.
That means the ((z*)0) has to be a pointer to a class or structure... but how's it work? That's not a dereference, since things are dereferenced with the '*' before the variable name. And why the '0'? This has got to be the weirdest piece of C code I've ever seen.
I know it has to return an int, since that's the final cast. Also, I know it's an address location, because of the &. But what does the ((z*)0) do? Ohh, I'm so confused. C masters, please help!
My guess is that z would be some class type, and that the "&(((z*)0)->w)" is the address of the declaration of w in memory, if that's possible. That really doesn't seem right though!
Last edited by Riskbreaker; February 23rd, 2003 at 05:03 AM.
-
February 23rd, 2003, 05:26 AM
#2
It looks like a perfect way to get NULL-pointer exception, but I am
not sure. Check out /P compiler switch - it allows to see the code
after preprocessor. This helps to understand crazy macros.
-
February 23rd, 2003, 06:25 AM
#3
MACRO (z,w) ( (int) ( &(((z*)0)->w) )
z is a structure(class) name and w is a member
struct z {
//...
type w;
};
and the MACRO returns which byte from the strusture w thakes
if you have en element
z myz;
&myz + MACRO(z, w) will return the address of w in myz
or &(myz.w)
It's only when you look at an ant through a magnifying glass on a sunny day that you realise how often they burst into flames
-
February 23rd, 2003, 07:42 AM
#4
Actually, to be insufferably pedantic for a moment, it does nothing of the sort. There's a space between the word MACRO and the opening parenthesis, so it won't be parsed as a macro with arguments, but as a no-argument macro with the replacement text: (z,w) ( (int) ( &(((z*)0)->w) ), which is probably going to result in a syntax error.
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
-
February 23rd, 2003, 08:19 AM
#5
Thank you!
SeventhStar, you're dead on. The space between the macro and the arguments was my own sloppy fault. Thank you for clearing up that weird piece of code... you've made me a little bit smarter!
-Riskbreaker
-
February 25th, 2003, 08:06 AM
#6
this macro is usually known as "offsetof"
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|