如何使用_Generic定义在C中接受输入的通用函数?
我试图用C中的_Generic定义一个通用函数来获取输入,这是我写的如何使用_Generic定义在C中接受输入的通用函数?,c,generics,gcc,c11,C,Generics,Gcc,C11,我试图用C中的_Generic定义一个通用函数来获取输入,这是我写的 #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) 不是您声明的变量。在: #define readlong(x
#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)
不是您声明的变量。在:
#define readlong(x) scanf("%11d",&x);
您添加了(x)。这将不允许您在没有它们的情况下使用readlong。您可以将助手定义为函数而不是宏。我修改了
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)
有帮助吗?@MichaelWalz我已经读过了。删除
在之后定义行。@n.m.这当然不重要。在宏扩展的中间不需要分号。移除它们并修复rgon91所说的内容。我已经尝试将readlong
更改为readlong(x)
,但在这种情况下,我得到了错误:`error:called object不是函数或函数指针#define scan(x)_Generic((x)`
#define readlong(x) scanf("%11d",&x);
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)