Reputation: 1
I'm wondering if we can declare something like below. My requirement was to use same variable but different structures. Can you guys help me if the below can be done? Please suggest if there are other options as well.
switch(x)
{
case 1:
struct_1 *name = NULL;
break;
case 2:
struct_2 *name = NULL;
break;
case 3:
struct_3 *name = NULL;
break;
default:
}
Regards
Upvotes: 0
Views: 762
Reputation: 175
void pointers can be dereferenced, otherwise they would be mostly useless. But the compiler needs to know what data type the pointer is pointing to, so you have to use a typecast whenever you want to acces the data the pointer is pointing to.
miikkas answer above already shows an example of how the typecast looks like.
Upvotes: 0
Reputation: 818
To be able to use the same variable name for different types, you could also use a union
of the different types and declare the variable of that union
type before the switch
statement.
Example code:
typedef union {
struct_1 s1;
struct_2 s2;
struct_3 s3;
} anyof123;
and before the switch
statement:
anyof123 *name = malloc(sizeof(anyof123)); // Example, allocate some memory.
and in the switch
statement:
case 1:
{
struct_1 s1 = ...; // Just an example, fill with your own declaration.
name->s1 = s1;
}
break;
and the resulting variable name
can be accessed outside the switch
scope afterwards.
As pointed out by Kavan Shah, you could use a void
pointer and remember to cast it to the wanted type each time you access it, like this:
((struct_1*)name)->my_data = ...;
Upvotes: 0
Reputation: 11
If I understand that you want to keep same variable "name" and use it later on as pointer to structure selected by case. Then you can use void *name (declare before switch), and in each case type-cast this pointer as per the desired structure pointer. And use "name" later on as and when required.
Upvotes: 0
Reputation: 409196
Case labels don't introduce a new scope. You either have to declare them before the switch
with different names, or enclose the code in each case in braces like
case 1:
{
struct_1 *name = NULL;
...
}
break;
case 2:
{
struct_2 *name = NULL;
...
}
break;
Upvotes: 5