cgenericskeywordc11winlibs

How to use C11 keyword _Generic with struct?


Related

Good day, everyone!

I am writing an macro that differentiate type of input struct. I am using MinGW GCC under Windows from WinLibs: https://winlibs.com/

An example from here: Syntax and Sample Usage of _Generic in C11 works great, and I was able to write same macro(Ex. A)

// Example A (Single Value):

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

//
typedef int32_t     i32;
typedef uint32_t    u32;
typedef int64_t     i64;
typedef uint64_t    u64;

// any single value
#define deb_single(val)                                     \
    printf("[%s]: ", #val);                                 \
    _Generic( (val),                                        \
        default : puts("UNKNOWN_TYPE"),                     \
        i32     : printf("[%d]"   ,   (i32)val),            \
        u32     : printf("[%u]"   ,   (u32)val),            \
        i64     : printf("[%lld]" ,   (i64)val),            \
        u64     : printf("[%llu]" ,   (u64)val)             \
    );                                                      \
    printf("Func [%s], line [%d]\n", __func__, __LINE__);

i32 main()
{
    i32 A = 111;
    u32 B = 222;
    i64 C = 333;
    u64 D = 444;

    deb_single(A);
    deb_single(B);
    deb_single(C);
    deb_single(D);

    return 0;
}
// Result_of Example A:

[A]: [111]Func [main], line [35]
[B]: [222]Func [main], line [36]
[C]: [333]Func [main], line [37]
[D]: [444]Func [main], line [38]

// Endof Example A.

Now, almost same approach (with typeof) works with structs of two same-type values (Ex. B)

// Example B (Struct of two same-type values):

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

//
typedef int32_t     i32;
typedef uint32_t    u32;
typedef float       r32;
typedef double      r64; // only for printf cast

typedef struct _tag_v2i { i32 x; i32 y; } v2i;
typedef struct _tag_v2u { u32 x; u32 y; } v2u;
typedef struct _tag_v2f { r32 x; r32 y; } v2f;

// 
#define deb_struct(str)                                                     \
    printf("[%s] @ line [%d]: ", #str, __LINE__);                           \
    _Generic( (typeof(str)){0},                                             \
        default : puts("UNKNOWN_TYPE"),                                     \
        struct _tag_v2i : printf("[%d][%d]\n", (i32)str.x, (i32)str.y),     \
        struct _tag_v2u : printf("[%u][%u]\n", (u32)str.x, (u32)str.y),     \
        struct _tag_v2f : printf("[%.2f][%.2f]\n", (r64)str.x, (r64)str.y)  \
    );

i32 main()
{
    v2i vA = {111,999};
    v2u vB = {222,888};
    v2f vC = {1.5f, 5.25f};

    deb_struct(vA);
    deb_struct(vB);
    deb_struct(vC);

    return 0;
}
// Result_of Example B:

[vA] @ line [30]: [111][999]
[vB] @ line [31]: [222][888]
[vC] @ line [32]: [1.50][5.25]

// Endof Example B.

However, I struggle to mix single values and structs (Ex. C)

// Example C [/*ERRORS*/]:

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

//
typedef int32_t i32;
typedef struct _tag_v2i { i32 x; i32 y; } v2i;

// 
#define deb_struct(str)                                                     \
    printf("[%s] @ line [%d]: ", #str, __LINE__);                           \
    _Generic( (typeof(str)){0},                                             \
        default : puts("UNKNOWN_TYPE"),                                     \
        i32             : printf("[%d]"      , (i32)str),                   \
        struct _tag_v2i : printf("[%d][%d]\n", (i32)str.x, (i32)str.y)      \
    );

i32 main()
{
    i32 sA = 555;
    v2i vA = {111,999};

    deb_struct(sA);
    deb_struct(vA);

    return 0;
}

// Result_of Example C:

error: request for member 'x' in something not a structure or union
   14 |         struct _tag_v2i : printf("[%d][%d]\n", (i32)str.x, (i32)str.y),     \

error: request for member 'y' in something not a structure or union
   14 |         struct _tag_v2i : printf("[%d][%d]\n", (i32)str.x, (i32)str.y),     \

error: aggregate value used where an integer was expected
   23 |     deb_struct(vA);

// Endof Example C.

So, my question is: how to make macro that takes as input single values AND struct (Ex. C)?

Thank you!


Solution

  • The reason for this is that all cases of _Generic will be expanded with the macro. To avoid that, the type-specific part needs to be moved outside the _Generic expression. We can achieve this if we replace your printf calls with calls to custom functions - then place the parameter to those functions outside of _Generic.

    And in order to not having to pass structs etc by value, maybe make those custom functions accept a pointer instead.

    Misc code review not directly related to the question:

    Cleaned up code:

    #include <stdio.h>
    #include <stdint.h>
    #include <inttypes.h>
    
    typedef struct
    { 
      int32_t x; 
      int32_t y;
    } v2i;
    
    static void print_int32_t (const int32_t* obj)
    {
        printf("[%"PRIi32"]\n", *obj);
    }
    
    static void print_v2i (const v2i* obj)
    {
        printf("[%"PRIi32"][%"PRIi32"]\n", obj->x, obj->y);
    }
    
    #define deb_struct(obj)                            \
        printf("[%s] @ line [%d]: ", #obj, __LINE__);  \
        _Generic((obj),                                \
            int32_t: print_int32_t,                    \
            v2i:     print_v2i                         \
        ) (&(obj))
    
    int main (void)
    {
        int32_t sA = 555;
        v2i vA = {111,999};
        deb_struct(sA);
        deb_struct(vA);
    }
    

    Now print_int32_t and print_v2i are function designators which will be called with the (&(obj)) part as parameter. So if we pass an int32_t to _Generic, then it will pick function print_int32_t and call it as print_int32_t(&sA).

    Output:

    [sA] @ line [32]: [555]
    [vA] @ line [33]: [111][999]