-2
//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
  ...
}

我只想在 if 块中执行一次代码行。

当然我知道如何通过不同的方式做到这一点(评论部分)。

但我想知道为什么我的代码不能按预期工作。

谢谢。

4

2 回答 2

3

预处理器指令将在编译期间发生。这意味着,在您的程序运行之前,它将需要:

//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));
    }

    ...
}
于 2017-10-13T15:25:55.897 回答
0

你走错路了。#ifdef是预处理器命令,在编译器之前解析。这意味着#ifdef如果条件不满足,则在编译之前将简单地删除块中的所有内容。

对于您的特定问题,使用静态变量的常用方法之一是:

int my_func()
{
    static int initialized = 0;

    if (!initialized)
    {
        /* Initialize */
        ...

        initialized = 1;
    }

    ...
}
于 2017-10-13T15:24:06.223 回答