【发布时间】:2016-10-17 22:20:31
【问题描述】:
我试图学习如何使用“新的”C11 Generic 表达式,但我碰壁了。
考虑以下代码:
#include <stdlib.h>
#include <stdio.h>
#define test(X, Y, c) \
_Generic((X), \
double: _Generic((Y), \
double * : test_double, \
default: test_double \
), \
int: _Generic((Y), \
int * : test_int, \
default: test_int \
) \
) (X, Y, c)
int test_double(double a, double *b, int c);
int test_int(int a, int *b, int c);
int test_double(double a, double *b, int c) { return 1; }
int test_int(int a, int *b, int c) { return 2; }
int main()
{
double *t = malloc(sizeof(double));
int *s = malloc(sizeof(int));
int a1 = test(3.4, t, 1);
int i = 3;
int a2 = test(i, s, 1);
printf("%d\t", a1);
printf("%d\n", a2);
return 0;
}
这一切都很好,但我仍然不明白为什么“_Generic((Y), ...”中的那些默认情况是必要的,而我可以在“_Generic((X), . .." 没有后果。
事实上,如果我删除这两个默认值,我会收到一个错误 (gcc 5.4.0),说 "selector of type 'double *' is not compatible with any association" while macro-expanding " int a1 = test(3.4, t, 1);"在宏扩展 test(i, s, 1)
时与 "int *" 相同“默认”真的有必要还是我遗漏了什么? 在第一种情况下,为什么会这样呢?如果我只有 test_double 和 test_int 可以调用,为什么我应该为甚至不应该编译的东西设置默认情况?
【问题讨论】:
-
您的描述令人困惑。如果您删除 Generic 中的默认值(Y 会出现错误?
-
是的,没错。粗体字。
标签: c generics macros default c11