C11 _Generic: how to deal with string literals?

前端 未结 3 1585
悲&欢浪女
悲&欢浪女 2020-12-03 10:21

Using the _Generic feature in C11, how do you deal with string literals?

For instance:

#include 
#define foo(x) _Generic(         


        
3条回答
  •  眼角桃花
    2020-12-03 10:41

    I have figured out a way to avoid using the clever (0,x) trick.

    If you use a string literal the type is char[s] , where s is the size of the string literal.

    How do you get that size?, use sizeof operator:

    #include 
    
    #define Test( x )   _Generic( ( x ) ,   char*: puts ,                   \
                                            const char*: puts ,             \
                                            const char[sizeof( x )]: puts , \
                                            char[sizeof( x )]: puts )( x )
    
    int main(void) 
    {
    
        char str[] = "This" ;
        Test( str ) ;
    
        Test( "works" ) ;
    
        char str2[10] = "!!!" ;
        Test( str2 ) ;
    
    return 0;
    }
    

    I tried compiling it with clang and Pelles and it worked.

    The only problem you still have to cast variable length arrays.

    After trying some more I found another analogue way of doing what Pascal Cuoq did, use &* operators:

    #include 
    #define foo(x) _Generic( ( &*(x) ), char*: puts , const char*: puts )( x )
    
    int main()
    {
        foo("Hello, world!");
        return 0;
    }
    

提交回复
热议问题