Discussion Locked

C/C++ Code Question - #define

0 helpful
2 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Hi,

A colleague has asked me the following question, and I am stumped. Can anyone help?

Thanks alot,

Frank

Question:

#define XYZ(a, b) (int)(&(((a *)0)->b))

What does this following macro do?

How and why might it be used?

2 replies

by john torjo

It's used to find out the offset of a variable within an instance of a class. I definitely don't recommend using it.

Here's an example:

#include
#define XYZ(a, b) (int)(&(((a *)0)->b))

class CTest
{
public:
int i;
bool b;
char c;
long l;
};

int main(int argc, char* argv[])
{
std::cout << "offset of i= " << XYZ( CTest, i) << std::endl ;
std::cout << "offset of b= " << XYZ( CTest, b) << std::endl ;
std::cout << "offset of c= " << XYZ( CTest, c) << std::endl ;
std::cout << "offset of l= " << XYZ( CTest, l) << std::endl ;
std::cin.get();
return 0;
}

In our example, for VC6, an instance of CTest takes 12 bytes.
You can use XYZ to know where - within these 12 bytes - each member variable is.
On VC6, this means:
- i takes the bytes 0-3
- b takes the byte 4
- c takes the byte 5
- l takes the bytes 8-11
(notice that bytes 6-7 are unused).

Hope this helps.

Best,
John

This discussion is closed to new replies.