C11 _Generic:如何处理字符串? [英] C11 _Generic: how to deal with string literals?
问题描述
在C11使用 _Generic
功能,你如何处理字符串?
Using the _Generic
feature in C11, how do you deal with string literals?
例如:
#include <stdio.h>
#define foo(x) _Generic((x), char *: puts(x))
int main()
{
foo("Hello, world!");
return 0;
}
给出了铿锵这个错误:
gives this error on clang:
controlling expression type 'char [14]' not compatible with any generic association type
更换的char *
与的char []
给我
error: type 'char []' in generic association incomplete
得到这个编译的唯一途径(据我所知)是:
The only ways (to my knowledge) of getting this to compile are:
- 铸字符串到合适的类型。这是丑陋的(在我看来)击败
_Generic
的摆在首位的位置。 - 使用
的char [14]
作为类型说明符。您的获得的是在开玩笑......
- Cast the string literal to an appropriate type. This is ugly and (in my view) defeats the point of
_Generic
in the first place. - Use
char[14]
as the type specifier. You have got to be kidding me...
我的假设是,传递给 _Generic
的时候,却显然不是阵列会衰减到指针。那么,怎样的做的我用 _Generic
与字符串?是那些只有两个选项?
My assumption was that arrays would decay to pointers when passed to _Generic
, but evidently not. So, how do I use _Generic
with string literals? Are those the only two options?
我使用的是Debian上的铛的3.2。不幸的是,它是唯一的编译器我有机会获得支持此功能,所以我不能告诉如果它是一个编译器错误或没有。
I'm using clang 3.2 on Debian. Unfortunately, it's the only compiler I have access to that supports this feature, so I can't tell if it's a compiler bug or not.
推荐答案
下面是一个解决方案:
#include <stdio.h>
#define foo(x) _Generic((0,x), char*: puts(x))
int main()
{
foo("Hello, world!");
return 0;
}
这编译和生产:
$ clang t.c && ./a.out
Hello, world!
这是有点跛,但我没有找到什么更好的办法让 X
衰减到一个字符指针,也不在您需要的模糊时尚相匹配的类型,与苹果LLVM 4.2版(铛-425.0.28)(基于LLVM 3.2svn)。
It is somewhat lame, but I did not find any better way to make x
decay to a pointer to char nor to match its type in the fuzzy fashion that you require, with Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn).
据的这个博客帖子由延猛吹,海湾合作委员会的行为是不同的(在GCC,字符串自动衰减在 _Generic
上下文指针,很明显)。
According to this blog post by Jens Gusted, GCC's behavior is different (in GCC, strings automatically decay to pointer in a _Generic
context, apparently).
顺便说一句,在C,一个字符串类型为字符
,而不是为const char的
。拒绝的char []
为类型名称的中的通用关联的不是一个编译器错误:
By the way, in C, the type of a string literal is array of char
, not of const char
. Rejecting char []
as type-name in a generic-association is not a compiler bug:
一个通用的选择应不超过一个默认的通用关联。在一个通用的关联类型名称应当指定的完成对象不是可变类型其他类型。 (6.5.1.1:2我的强调)
A generic selection shall have no more than one default generic association. The type name in a generic association shall specify a complete object type other than a variably modified type. (6.5.1.1:2 with my emphasis)
这篇关于C11 _Generic:如何处理字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!