Search code examples
ccastingtypecasting-operator

Typecast variable basing on parameters


In C, I want to typecast a variable to different variable basing on Variable. How do I make it dynamic? Like

Greedy way

    if ( typecast_to_uint16 == 1 ) {
            uint16 v = (uint16)val;
    } else if (typecast_to_char == 1) {
            char p = (char )val;
    } else if (typecast_to_some_struct_a == 1) {
            struct a b = (struct_a)val;
    }

This is a greedy way, Is there any Optimized or Dynamic way where I can typecast a variable directly something like using a struct ??

Like eg:

     (type_cast_array[struct_a_index]) ret_val;

Editing the question to clear confusion..


Solution

  • This can't be done without runtime checks, and you have to do those yourself.

    C is a static compiled language, and does not support manipulating types as first class values. That is, you can't put the type of a variable in a different variable and e.g. cast to that type indirectly.

    This is because the actual machine code that manipulates values is generated at compile-time, and the compiler has to know the types of things in order to generate the proper instructions.

    As mentioned in comments, a tagged union is often a way to model variables of varying type cleanly.