【问题标题】:ISO C equivalent of braced-groups within expressions表达式中括号组的 ISO C 等效项
【发布时间】:2009-10-26 18:12:26
【问题描述】:

如何以符合 (ISO C99) 的方式执行以下操作?

#define MALLOC(type, length, message) ({                                      \
         type * a_##__LINE__ = (type *)malloc((length) * sizeof(type));       \
         assert(message && (a_##__LINE__ != NULL));                           \
         a_##__LINE__;                                                        \
      })

double **matrix = MALLOC(double *, height, "Failed to reserve");

注意:编译我使用:gcc -std=c99 -pedantic ...

【问题讨论】:

    标签: c gcc macros


    【解决方案1】:

    您不应该将malloc() 的测试放在assert() 中:当您进行发布构建时,它不会被编译。我没有在下面的程序中使用assert()

    #include <stdio.h>
    #include <stdlib.h>
    
    void *mymalloc(size_t siz, size_t length,
                   const char *message, const char *f, int l) {
      void *x = malloc(siz * length);
      if (x == NULL) {
        fprintf(stderr, "a.out: %s:%d: MALLOC: "
                        "Assertion `\"%s\" && x != ((void *)0)' failed.\n",
              f, l, message);
        fprintf(stderr, "Aborted\n");
        exit(EXIT_FAILURE);
      }
      return x;
    }
    
    #define MALLOC(type, length, message)\
          mymalloc(sizeof (type), length, message, __FILE__, __LINE__);
    
    int main(void) {
      int height = 100;
      double **matrix = MALLOC(double *, height, "Failed to reserve");
      /* work; */
      free(matrix);
      return 0;
    }
    

    【讨论】:

    • 我将按照您的建议使用一个函数并避免出现 heisenbug(感谢您指出)。
    【解决方案2】:

    没有与您正在使用的 GCC 扩展等效的标准。

    您可以使用函数(如果您使用 C99,甚至可能是内联函数)代替宏中的代码来实现等效结果。您仍然需要一个宏来调用该函数,因为其中一个参数是“类型名称”,您不能将它们传递给函数。

    查看@pmg 的回答,了解函数类型和使用它的宏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-20
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多