3

I'm using the online compiler and debugger for C. This webpage uses GCC 5.4.1 C99. When I test this code,

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;
}

The error message is

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
                 ^~~~

This compiler supports _Generic but I have this problem when using {} brackets.

How can I solve this when I want to initialize the array using the _Generic keyword?

0

1 Answer 1

1

_Generic does not work this way. It is not a "classic" macro. It has to understand the types and it is "expanded" to the value or code by the compiler.

#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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.