2016-10-17 25 views
1

我试图定义一个通用的函数使用C中_Generic采取输入,这是我写的如何定义通用函数以使用_Generic在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) 
+0

请问[此问题](http://stackoverflow.com/questions/9804371/syntax-and-sample-usage-of-generic-in-c11)有帮助吗? –

+0

@MichaelWalz我已经读过那篇了。 – Yogendra

+0

在'#define'行之后删除';'。 –

回答

0

你可以定义你的助手是函数而不是宏。我修改了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) 
0
readlong 

不是您声明的变量。在:

#define readlong(x) scanf("%11d",&x); 

您添加(x)。这不会让你在没有它们的情况下使用readlong。

+0

我已经尝试将'readlong'改为'readlong(x)',但是在那种情况下我得到错误:'错误:调用的对象不是函数或函数指针 #define scan(x)_Generic((x),\'' – Yogendra

相关问题