What does the following macro do?

血红的双手。 提交于 2020-01-06 14:47:35

问题


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.


回答1:


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.




回答2:


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




回答3:


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.)



来源:https://stackoverflow.com/questions/3453063/what-does-the-following-macro-do

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!