1

Is there some easy way of storing and restoring different types in one variable?

I thought about using:

typedef enum {
    float_e, int_e, char_e
} types;

typedef struct {
    types type;
    void *data;
} array_t;

Or this:

typedef enum {
    float_e, int_e, char_e
} types;

typedef struct {
    types type;
    union {
        float f;
        int i;
        char c;
    }
} array_t;

And then I'd like to use the data in many different functions, but I don't want to use in every function switch to check what datatype it stores. Is there some easier way to do it?

hat
  • 781
  • 2
  • 14
  • 25
Paprikadobi
  • 114
  • 1
  • 6
  • Say you have this `magic_type_t`. How would you use it? – Eugene Sh. Jul 30 '18 at 17:27
  • 3
    What's the goal of doing it that way? If you're trying to implement something akin to generics i.e. a sort that can take a float, int or a char you can either use a straightforward implementation of overloading, or using macros. https://stackoverflow.com/questions/16522341/pseudo-generics-in-c – Eric Yang Jul 30 '18 at 17:29
  • As I said in different functions, for example searching for value in that array or adding some number to all elements, ... – Paprikadobi Jul 30 '18 at 17:30
  • @Eric Yang Thanks, I'm quit new to c so I didn't now something like this exists – Paprikadobi Jul 30 '18 at 17:31
  • @Eric Yang, It really worked, thanks, now I only would like to ask, if you now, how could I print now the values? – Paprikadobi Jul 30 '18 at 17:45
  • this is why C++ has function overloading. No tricks needed – 0___________ Jul 30 '18 at 17:59
  • @EricYang it is only compile time solution. – 0___________ Jul 30 '18 at 18:02
  • C is a compiled language. I don't see the issue. As for printing it out, you're going to have to use a similar trick and define a generic printf – Eric Yang Jul 30 '18 at 18:15
  • @P__J__, C also has function overloading. I think that the question was how to implement generics so you don't have to repeat the code logic with a bunch of overloaded functions – Eric Yang Jul 30 '18 at 18:16
  • OK, now last question, and what about that struct? I found on iternet it should be like `array_t##TYPE`, but it gives me error. – Paprikadobi Jul 30 '18 at 18:21
  • 1
    C does not have. Preprocessor string concatenation is not overloading – 0___________ Jul 30 '18 at 18:44
  • C does have generic functions. Though they're mostly of limited use. If you don't want to check the type with `if`, you can use the function pointer or virtual table approach to dispatch methods. This is how for example CPython does its magic in C – Antti Haapala -- Слава Україні Jul 30 '18 at 19:58

0 Answers0