3

我正在使用 C 的在线编译器和调试器。这个网页使用 GCC 5.4.1 C99。当我测试这段代码时,

https://www.onlinegdb.com/online_c_compiler

#include <stdio.h>
#include <stdint.h>
#define SIMPLE(T) _Generic( (T), char: 'x', int: 2, long: 3, default: 0)
#define BRAC(T) _Generic( (T), uint8_t*: {1, 1}, uint16_t*: {2, 2}, default: {0xFA, 0xFA})

int main(){
    int num = SIMPLE(777); // this works
    uint8_t arr[] = BRAC("DEFAULT"); // error: expected expression before ‘{’ token
    printf("num = %d\n", num); // prints 2
    printf("0x%x\n", arr[1]);
    return 0;
}

错误信息是

main.c: In function ‘main’:
main.c:4:42: error: expected expression before ‘{’ token
 #define BRAC(T) _Generic( (T), uint8_t*: {1, 1}, uint16_t*: {2, 2}, default: {0xFA, 0xFA})
                                          ^
main.c:8:21: note: in expansion of macro ‘BRAC’
     uint8_t arr[] = BRAC("DEFAULT"); // error: expected expression before ‘{’ token
                 ^~~~

这个编译器支持 _Generic 但我在使用 {} 括号时遇到了这个问题。

当我想使用 _Generic 关键字初始化数组时,如何解决这个问题?

4

1 回答 1

1

_Generic 不能以这种方式工作。它不是“经典”宏。它必须了解类型,并由编译器“扩展”为值或代码。

#include <stdio.h>
#include <stdint.h>
#include <string.h>

#define SIMPLE(T) _Generic( (T), char: 'x', int: 2, long: 3, default: 0)
#define BRAC(T) _Generic( (T), uint8_t*: (uint8_t []){1, 1}, uint16_t*: (uint8_t []){2, 2}, default: (uint8_t []){0xFA, 0xFB})

int main(){
    int num = SIMPLE(777); // this works
    uint8_t *arr = BRAC("DEFAULT"); 
    uint8_t arr1[2];
    memcpy(arr1, BRAC("DEFAULT"), sizeof(arr1));
    printf("num = %d\n", num); // prints 2
    printf("0x%x\n", arr[1]);
    printf("0x%x\n", arr1[0]);
    return 0;
}
于 2020-10-10T17:19:59.887 回答