如何在C11中使用_Generic
功能处理字符串字面量?
例如:
#include <stdio.h>
#define foo(x) _Generic((x), char *: puts(x))
int main()
{
foo("Hello, world!");
return 0;
}
在clang上会产生以下错误:
controlling expression type 'char [14]' not compatible with any generic association type
将char *
替换为char[]
给我带来了
error: type 'char []' in generic association incomplete
据我所知,使这段代码能够编译的唯一方法有:
- 将字符串文字转换为适当的类型进行强制转换。这样做很丑陋,并且(在我看来)违反了使用
_Generic
的初衷。 - 使用
char[14]
作为类型指定符。你一定是在开玩笑吧...
我的假设是,当传递给 _Generic
的参数是数组时,它们会自动退化为指针,但显然不是这样。那么,我应该如何使用字符串文字与 _Generic
一起使用呢?这两个选项是唯一的选择吗?
我在 Debian 上使用的是 clang 3.2。不幸的是,这是我唯一可以访问支持此功能的编译器,因此我无法确定它是否是编译器错误。