Steve H
Steve H

Reputation: 493

Anonymous union in C

I am trying understand anonymous unions for a use case I have. The use-case is to be able to use different prototypes of a given method within a function pointer table. For example in the following code snippet myfunc can have two variants, one that accepts only a string; and one that can accept 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;
}

Example me1 and me2 seem to provide correct results. But example me3. Where I am trying to statically initialize the union within structure, 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 someone point out the right way of initializing an anonymous union within the structure.

Edit: I was declaring the struct wrong in a very clearly wrong way, correct way-

static const my_struct_t me3 = {myfuncEx_imp};

Upvotes: 4

Views: 645

Answers (1)

Alcamtar
Alcamtar

Reputation: 1582

I ran into this yesterday. You cannot initialize a union without also specifying the union member. Otherwise it is ambiguous. So,

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

Upvotes: 2

Related Questions