Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Can I store a type as a variable in C?

Name: Anonymous 2008-06-08 7:24

printf("Hello World, /prog/\n");

I was wondering if there is a good way to store a C data type as a variable, and later use that variable for the declaration of return types and variable types (in the form of a cast would be fine), or as function argument for polymorphic fun.

Name: Anonymous 2008-06-09 20:12

its not hard at all. create a struct with a union of all of the types in c inside of it, and an enum to tell you which type it is

like so:


enum c_type {
  INT,
  SHORT,
  USHORT,
  ULONG,
  ...
};

struct type {
  enum c_type type;
  union {
    int a;
    short b;
    unsigned short c;
    unsigned long d;
    ...
  } storage;
};


then in your functions just do


if(var.type == INT)
  printf("%d\n", var.storage.a);
else if(var.type == CHAR)
  printf("%c\n", var.storage.z);

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List