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'
CodePudding user response:
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;
...
}
CodePudding user response:
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]
}
CodePudding user response:
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.