Declare a generic variable type

I am trying to declare a generic variable type in C (I cannot use C ++), and I mean the following parameters.

Option1

typedef struct 
{
     void *value;
     ElementType_e type;
} Data_t;

Option 2

typedef struct {
    ElementType_e type;
    union {
        int a; 
        float b; 
        char c;
    } my_union;
} my_struct;

where ElementType_e is an enumeration that contains all possible types of variables (for example, int, char, unsigned int, etc.). I seem to be inclined to option 1, because I do not believe that casting will add extra computing time compared to the switch, right?

I'm just wondering which type is more useful? I know that option 1 will require use with every use / access. Are there any possible problems that may arise during casting (especially when running / compiling code on another platform, for example, 32 bits and 16 bits of micro)

2 () (, ,...).

, 2 ( ), . C [void *]

+4
3

- ,

, , / void -pointer ( C).

, ?

, ,

  • 1 ( , ).
  • 2 ( type-save, 1, "" , ElementType_e).

comment:

, ( ), / ( - , 1 ).

+4

. , :

union sockaddr_u {
    struct sockaddr_storage ss;
    struct sockaddr_in sin;
    struct sockaddr_in6 sin6;
};

, IPv4 IPv6. (ss.ss_family, sin.sin_family sin6.sin6_family).

+2

, , , . , , :

typedef char S0_t;
typedef struct { S0_t x; } S1_t;
typedef struct { S1_t x; } S2_t;
typedef struct { S2_t x; } S3_t;

, , , .
, .

, , , .
, , , .
, , - , , :

 typedef void* generic_t;
+1

All Articles