gpt4 book ai didi

c - 如何使用 _Generic 定义通用函数以在 C 中接受输入?

转载 作者:太空宇宙 更新时间:2023-11-03 23:43:22 24 4
gpt4 key购买 nike

我试图在 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)

最佳答案

您可以将助手定义为函数而不是宏。我修改了 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 定义通用函数以在 C 中接受输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40089555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com