开发者

What does the following macro do?

in qemu source code, I have the following macro named offsetof. Can anybody tell me what it does?

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *) 0)->MEMBER)

It's used in this manner :

offsetof(CPUState,开发者_如何学编程 icount_decr.u32)

where CPUState is a struct.

I think it gives the offset of the member inside a struct, but I'm not sure.

EDIT:Yeah, I found out what was happening. The definition of CPUState had a macro inside, which I missed, which included the variable icount_decr.


It gets the offset of the member of a struct. It does so by casting address zero to a struct of that type then taking the address of the member.


Your thinking is correct! And the name of the macro gives a good hint, too. ;)


It's defined in §7.17/3:

offsetof(type, member-designator)
which expands to an integer constant expression that has type size_t, the value of which is the offset in bytes, to the structure member (designated by member-designator), from the beginning of its structure (designated by type). The type and member designator shall be such that given
static type t;
then the expression &(t.member-designator) evaluates to an address constant. (If the specified member is a bit-field, the behavior is undefined.)

Because the library doesn't have to necessarily follow language rules, an implementation is free to get the result however it pleases.

So the result of this particular implementation is not undefined behavior, because you aren't suppose to care how it's implemented. (In other words, your implementation makes the guarantee that taking the address of an indirection through a null pointer is well-defined. You of course can't assume this in your own programs.)

If that some library has (re)defined offsetof, they've made your program behavior undefined and should be using the standard library instead. (The dummies.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜