Search code examples
cunions

How to re-use a variable without getting error C2371 (Redefinition), for var with different types?


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!


Solution

  • You could use a union and you might also want to define an enum for the response type:

    typedef enum { 
        RESPONSE_1,
        RESPONSE_2,
        RESPONSE_3,
        RESPONSE_4
    } ResponseType;
    
    typedef struct {    
        ResponseType type;
        union {
            RESPONSE1 rsp1;
            RESPONSE2 rsp2;
            RESPONSE3 rsp3;
            RESPONSE4 rsp4;
        };
    } Response;
    

    In your code you use it like this:

    Response r;
    switch (command) {
        case CMD1:
            r.type = RESPONSE_1;
            memcpy(&r.rsp1, pPkt, sizeof(r.resp1));
            break;
        case CMD2:
        ...
    }