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,305
  • 1
  • 13
  • 26
  • 1
    Exactly. M. Sharpe, please tell us what you are trying to achieve with the value that may be of a dynamically decided type! There is almost certainly a better solution. – Kilian Foth Jan 29 '18 at 07:48
  • I'm doing a recreation of the printf function. Pretty sure that what I'm asking for is done with that function through the flags, (h, hh, l, ll, etc...) and is probably easy to do if I write a lot of conditional statements. I was hoping that I wouldn't need to do that. – M. Sharpe Jan 29 '18 at 20:33
  • You can check instead of being "pretty sure": https://sourceware.org/git/?p=glibc.git;a=blob;f=stdio-common/vfprintf.c;h=3b87740dd990f2ab6875d5efd5e1b7be2cf62a51;hb=HEAD – Mael Jan 30 '18 at 09:26
  • I was looking for this before, but I'm glad I didn't find it. Too many things I can't use based off the rules I'm working under. My version may not be optimized but it works for the most part. I asked the people directly around me, and they gave me about 5 different ways to do this. 2 involving bit switches and 3 using the dispatcher table architecture that I had been using with my entire function up until this point. Not sure why I'm getting the negative vibes from my question, but I'll keep this in mind when I ask my next question. My first question seems to have been a bad one. – M. Sharpe Jan 30 '18 at 17:38