Hai*_*ile 4 c linux macros gcc
我正在学习c99,在阅读了有关结构的内容之后,我在Linux内核代码中找到了以下宏:
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))
Run Code Online (Sandbox Code Playgroud)
我..什么?用法:
#include <stdio.h>
#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))
struct book {
char title[100];
char author[100];
};
int main(void)
{
printf("%lu\n", FIELD_SIZEOF(struct book, title)); // prints 100
}
Run Code Online (Sandbox Code Playgroud)
这是扩展(gcc -E)
printf("%lu\n", (sizeof(((struct book*)0)->title)));
Run Code Online (Sandbox Code Playgroud)
真正让我感到困惑的是0。我取代它1,2,+1,-1,+999和'a'和"hello",和它始终工作。
在源中没有评论。我知道这->是用来通过指针访问结构成员的,但是指针又如何((struct book*)0)呢?宏如何工作?
这里的关键是sizeof由编译器在编译时计算的。因此,您指定的指针实际上不会被取消引用。毕竟,对象所在的位置不会改变其大小。该sizeof运营商将在类型方面完全评估其操作数。
因此,您使用的地址实际上是无关紧要的,但是0(NULL)是常见的选择。
| 归档时间: |
|
| 查看次数: |
808 次 |
| 最近记录: |