Passing variable type as function parameter

后端 未结 4 2007
孤独总比滥情好
孤独总比滥情好 2020-12-24 12:03

Is it possible to pass variable type as part of a function parameter, e.g.:

void foo(varType type)
{
  // Cast to global static
  unsigned char bar;
  bar =          


        
相关标签:
4条回答
  • 2020-12-24 12:23

    I don't see how you could do this in the general case, given that C is a statically typed language.

    The compiler needs to know at compile time what the type of type * is in order to be able to generate the reference to ->member.

    0 讨论(0)
  • 2020-12-24 12:27

    You can't do that for a function, because then it needs to know the types of the arguments (and any other symbols the function uses) to generate working machine code. You could try a macro like:

    #define foo(type_t) ({ \
        unsigned char bar; \
        bar = ((type_t*)(&static_array))->member; \
        ... \
        })
    
    0 讨论(0)
  • 2020-12-24 12:29

    You could make an enum for all different types possible, and use a switch to make the dereferencing:

    typedef enum {
        CHAR,
        INT,
        FLOAT,
        DOUBLE
    } TYPE;
    
    void foo(TYPE t, void* x){
        switch(t){
            case CHAR:
                (char*)x;
                break;
            case INT:
                (int*)x;
                break;
             ...
        }
    }
    
    0 讨论(0)
  • 2020-12-24 12:31

    Eh, of course you can. Just use a macro like so:

    #include <stdio.h>
    #define swap(type, foo, bar) ({type tmp; tmp=foo; foo=bar; bar=tmp;})
    
    int main() {
      int a=3, b=0;
      swap(int, a, b); //                                                                     
    0 讨论(0)
提交回复
热议问题