简体   繁体   中英

C _Generic and char arrays

I have a generic expression (in a macro):

int equal = _Generic(                                                                           
        (actual),                                                                               
        unsigned long:  actual == expected,                                                     
        int:            actual == expected,                                                     
        unsigned char:  actual == expected,                                                     
        char *:         strcmp((char *)actual, (char *)expected) == 0                           
);                                                                                              

When I expand it with actual being a char[12] it works on some architectures/compilers, but on some I get the error:

error: controlling expression type 'char [12]' not compatible with any generic association type

How can I handle this without writing a line for every single length of char array? ie char[0] , char[1] , char[2] ...

Forcing the char array to decay into a pointer would do the trick, but I cannot change this macro into a function. Is there a way to force decay? I have tried *&actual , but it does not result in a char * .

This problem is due to an ambiguity that was in the C11 text that introduced _Generic . It is now resolved by the committee in that it is expected that array to pointer conversion is performed to determine the matching type.

For the time being you can work around this by using your actual in an expression that does this conversion. I'd suggest

bool equal = _Generic(                                                                           
        (actual)+0,                                                                               
        default:  actual == expected,                                                     
        char *:         strcmp((char *)actual, (char *)expected) == 0                           
);

BTW, your code is not completely type save, because it doesn't check the type of expected . I'd try to have a second _Generic that ensures that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM