我试图用C语言中的泛型来定义一个接受输入的通用函数,这是我写的

#include  <stdio.h>

#define readlong(x) scanf("%lld",&x);
#define read(x) scanf("%lld",&x);

#define scan(x) _Generic((x), \
long long: readlong, \
default: read \
)(x)

但是当我在gcc 5.3.0上使用gcc test.c -std=C11编译它时,我得到错误:
error: 'readlong' undeclared (first use in this function)

最佳答案

您可以将助手定义为函数而不是宏我修改了scan以便它将地址传递给匹配的函数。

static inline int readlong (long long *x) { return scanf("%lld", x); }
static inline int readshort (short *x) { return scanf("%hd", x); }
static inline int unknown (void) { return 0; }

#define scan(x) _Generic((x), \
long long: readlong, \
short: readshort, \
default: unknown \
)(&x)

10-04 11:37