In VBA I simply would use a variant-Type for this, but how can I reduce this somewhat repetitive code to get to a better switch case block?
switch(command){
case CMD1:
RESPONSE1 rsp1;
memcpy(&rsp1,pPkt,sizeof(rsp1));
break;
case CMD2:
RESPONSE2 rsp2;
memcpy(&rsp2,pPkt,sizeof(rsp2));
break;
case CMD3:
RESPONSE3 rsp3;
memcpy(&rsp3,pPkt,sizeof(rsp3));
break;
case CMD4:
RESPONSE4 rsp4;
memcpy(&rsp4,pPkt,sizeof(rsp4));
case CMD5:
RESPONSE5 rsp5;
memcpy(&rsp5,pPkt,sizeof(rsp5));
default:
break;
}
My goal would be to eliminate those 5 response variables and use only one – however, I need the 5 different types because of the memcpy.
I am aware, that there is something like cast, but I think this is more problematic, because these RESPONSE# are structs of different size – wouldn’t I have to reallocate memory for that?
Edit:
Thanks to mux, I found, that there is already a union for that in my code (adapting something from someone else)!
typedef union
{
RESPONSE1 rsp1;
RESPONSE2 rsp2;
RESPONSE3 rsp3;
RESPONSE4 rsp4;
RESPONSE5 rsp5;
}
RESPONSE_UNION;
And this is what I am using now:
RESPONSE_UNION ru;
switch(command){
case CMD1:
memcpy(&ru.rsp1,pPkt,sizeof(ru.rsp1));
break;
case CMD2:
memcpy(&ru.rsp2,pPkt,sizeof(ru.rsp2));
break;
...
Really a great help!
You could use a
unionand you might also want to define anenumfor the response type:In your code you use it like this: