How do I have a variable in C that can take various types?

I am looking to implement a dictionary data structure in C that I want to be as general as possible. That is, it can take a pair of values, which can be of any type.

How can I initialize a variable that can accept any types?

And how can I convert this type back to the type I want? (Printed)

Thanks.

+3
source share
10 answers

In C there is no easy way to do this. You can use void * and pass pointers to types, but there is no concept of patterns or generics or variants that exist.

void *, , . void * , . , , .

Windows, ", .

+4

, , :

union uu {
  int i;
  float f;
  char c;
  char *s;
} x;

x.i - , x.s a char .., x .

, - - . :

 struct ss {
   int type;
    union {
      int i;
      float f;
      char c;
      char *s;
    } val;
  } x;

- :

 #define FLOAT 1
 #define INT   2
 .... 

 x.val.i = 12;
 x.type = INT;
 ....
 if (x.type = INT) printf("%d\n",x.val.i);
 ....

.

, , , , .

+8

, :

, , , , .

-, , struct { void * data; enum Type tag }

enum Type { int, char*, ... etc }

void * - , , , .

Type , , .

, , , Type void *

+7

, void *.

+2

:

void* foo;

, :

union my_types {
   int* i;
   char* s;
   double* d;
   bool* b;
   void* other;
}

"" - ( "my_types", ). . .

- ++ , .

+2

void *?

, , , .

+1

void. void ( ) .

" ", :

enum MyType { INTEGER, DOUBLE_STAR };
struct anytype {
    enum MyType mytype;
    size_t mysize;
    void *myaddress;
};

struct anytype any_1, any_2;
int num_chars;
double array[100];

any_1.mytype = INTEGER;
any_1.myaddress = &num_chars;
any_1.mysize = sizeof num_chars;

any_2.mytype = DOUBLE_STAR;
any_2.myaddress = array;
any_2.size = sizeof array;

,

foo(any_1);
foo(any_2);

foo

void foo(struct anytype thing) {
    if (thing.mytype == INTEGER) {
        int *x = thing.myaddress;
        printf("the integer is %d\n", *x);
    }
    if (thing.mytype == DOUBLE_STAR) {
        size_t k;
        double *x = thing.myaddress;
        double sum = 0;
        for (k = 0; k < thing.mysize; k++) {
            sum += thing.myaddress[k];
        }
        printf("sum of array: %f\n", sum);
    }
}

+1

void *, . - : - .

, , struct void * , . ; C - , , , , . struct void * , .

. , , ++ # Java.

0

enum _myType { CHAR, INT, FLOAT, ... }myType;
struct MyNewType
{
   void * val;
   myType type;
}

MyNewType . .

0

C offers joins that can suit your purposes, you need to define all types before compiling, but the same variable can point to all types that you include in the union.

0
source

Source: https://habr.com/ru/post/1723275/


All Articles