Using the _Generic
feature in C11, how do you deal with string literals?
For instance:
#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
Replacing char *
with char[]
gives me
error: type 'char []' in generic association incomplete
The only ways (to my knowledge) of getting this to compile are:
- 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...
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?
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…