Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare generic variable type

Tags:

c

I am trying to declare a generic variable type in C (I can't us C++), and I have in my mind the following options.

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 enum that holds all the possible type of variables (e.g. int, char, unsigned int, etc..). I am kinda leaning toward option 1, because I don't believe casting will add extra computational time, compared to switch, right?

I am just wondering which type is more useful? I know option 1 will require casting every-time being used/accessed. is there any possible issues that could happen with casting ( especially with running/compiling the code on different platform, e.g 32 bits and 16 bits micro)

While option2 require a switch () to do any operation (e.g. addition, ...).

The following link explained that Option 2 is better ( from readability point of view), but i mainly concern about the code size and computational cost. Generic data type in C [ void * ]

like image 957
ras red2004 Avatar asked Mar 15 '23 11:03

ras red2004


1 Answers

is there any possible issues that could happen with casting

No, as you do not want cast, as there is no need to cast when assigning from/to a void-pointer (in C).

I am just wondering which type is more useful?

Both do, so it depends, as

  • 1 is for the lazy (as it's few typing, and few different variables' names to remember).
  • 2 is for the cautious (as it's type-save, as opposed to option 1, where the "real" type info is lost, so you can even assign a variable's address of a type not in ElementType_e).

Referring a comment:

Regarding performance I expect no major difference between both approaches (if implemented sanely), as both options need condtional statments on assigning to/from (exception here are pointer variables, which for option 1 go without conditonal statements for assignment).

like image 176
alk Avatar answered Mar 25 '23 07:03

alk