ISO C相当于支撑-组前pressions内 [英] ISO C equivalent of braced-groups within expressions

查看:154
本文介绍了ISO C相当于支撑-组前pressions内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能做一个标准(ISO C99)的方式下?

How can I do the following in a compliant (ISO C99) way?

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

NB: to compile I use: gcc -std=c99 -pedantic ...

推荐答案

您不应该把为测试的malloc()断言():它不会当你做一个发布版本中进行编译。我没有使用下面的程序断言()

You shouldn't put the test for malloc() in an assert(): it won't be compiled in when you do a release build. I haven't used assert() in the following program.

#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;
}

这篇关于ISO C相当于支撑-组前pressions内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆