Anonymous union in C

I am trying to understand anonymous alliances for the use case that I have. The use case should be able to use different prototypes of this method in the table of function pointers. For example, in the following code snippet, myfunc can have two options: one that accepts only a string; and one that can take additional parameters.

Here is my code snippet -

typedef struct my_struct
{
    union{
            int (*myfunc)(char*);
            int (*myfuncEx)(char*, int);
    };

}my_struct_t;

int myfunc_imp(char* x)
{
    printf("This is myfunc_imp - %s\n", x);
}

int myfuncEx_imp(char* x, int y)
{
    printf("This is myfuncEx_imp - %s\n", x);
    printf("This is myfuncEx_imp - %d\n", y);
}

int main()
{
    char *string = "Hello World";
    my_struct_t me1, me2;
    me1.myfunc = myfunc_imp;
    me1.myfunc(string);

    me2.myfuncEx = myfuncEx_imp;
    me2.myfuncEx(string, 7);

    static const me3 = {myfuncEx_imp};
    me3.myfuncEx(string, 8);

    return 0;
}

The examples me1 and me2 seem to give the correct results. But an example is me3. Where I try to statically initialize the union inside the structure, it throws this error -

warning: initialization makes integer from pointer without a cast
error: request for member `myfuncEx' in something not a structure or union

Can anyone point out the correct way to initialize anonymous union within the structure.

Edit: I incorrectly indicated the structure incorrectly, the correct way is

static const my_struct_t me3 = {myfuncEx_imp};
+4
1

. . . ,

static const my_struct_t me3 = { .myfuncEx = myfuncEx_imp };
+1

Source: https://habr.com/ru/post/1610486/


All Articles