如何使用 _Generic 定义通用函数以在 C 中接受输入?
How to define general function to take input in C using _Generic?
我试图定义一个通用函数来在 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)
但是当我在 gcc 5.3.0 上使用 gcc test.c -std=C11
编译它时,出现错误:
error: 'readlong' undeclared (first use in this function)
readlong
不是您声明的变量。在:
#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)
我试图定义一个通用函数来在 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)
但是当我在 gcc 5.3.0 上使用 gcc test.c -std=C11
编译它时,出现错误:
error: 'readlong' undeclared (first use in this function)
readlong
不是您声明的变量。在:
#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)