简体   繁体   中英

Cast a void pointer to another type based on an input parameter

I am trying to create a variable of type A or B based on an input parameter and assign a casted void pointer to it.

void set_info_param(void* info, bool req)
{
    ...
    if (req)
        struct info *capa_info = (struct info *) info;
    else
        struct info_old *capa_info = (struct info_old *) info;
    ... [Use capa_info]
}

When I try to compile it I get the following error:

expected expression before 'struct'

Since you define new variables you need to put it into blocks like:

if (req)
{
    struct info *capa_info = (struct info *) info;
    ...
}
else
{
    struct info_old *capa_info = (struct info_old *) info;
    ...
}

In C declarations are not statements.

On the other hand, the if statement expects a sub-statement.

So if you want that the sub-statement of the if statement had a declaration then enclose the declaration in the compound statement like

if (req)
{
    struct info *capa_info = (struct info *) info;
}
else
{
    struct info_old *capa_info = (struct info_old *) info;
... [Use capa_info]
}

I am trying to create a variable of type A or B

This is not how C types works. Every variable has a type which is known statically at compile time. You cannot have a variable assume one of the two types based on a run-time condition. If you need two different types, you have to use two different variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM