0

I am trying to use a dispatch table to select a data type to cast something as and cannot figure out the syntax for this.

g_cast_table[] =
{
    {'h', short int}
          or
    {'h', "short int"}
}

outcome: (short int)q

Right now my table is set to have a char name and char* type. This is causing a large number of errors as I try to compile. Is there an actual way to do this or should I rethink my process?

1 Answers1

3

Types are not first-class values in C, so you can't write code that looks up a type to cast to depending on some runtime state. Your example is not even valid C.

Apart from that, how would you use such a code?

int n = magic_casting_function(x);

What would happen in the magic_casting_function for some reason decided that x should be cast to a char*? You shouldn't then assign it to an int.

As some more food for thought, what would magic_casting_function's signature be?

magic magic_casting_function(void *x);  // like this?

The closest thing to magic in the code above is void*, but... I don't think you should go that way and treat everything in your program as a bunch of void pointers.

You should "rethink your process", in my opinion.

Mael
  • 2,395
  • 1
  • 15
  • 26