预处理器指令将在编译期间发生。这意味着,在您的程序运行之前,它将需要:
//static int initialized;
void print(struct student *arg) {
#ifndef first_call
#define first_call 1
//if (!initialized) {
//initialized = 1;
printf("sizeof(*arg1): %lu\n", sizeof(*arg));
//}
#endif
...
}
并将其变成:
//static int initialized;
void print(struct student *arg) {
#define first_call 1
//if (!initialized) {
//initialized = 1;
printf("sizeof(*arg1): %lu\n", sizeof(*arg));
//}
...
}
这意味着,您的意图不会发生。你简单地定义first_call
为1。
像这样的临时变量initialized
将是使其运行一次的好解决方案。但请记住,退出此函数调用后,局部变量会被销毁。提示:查找静态变量..
这会起作用:
void print(struct student *arg)
{
static bool initialized = false;
if (!initialized)
{
initialized = true;
printf("sizeof(*arg1): %lu\n", sizeof(*arg));
}
...
}