freonix
freonix

Reputation: 1625

Passing variable type as function parameter

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 = ((type *)(&static_array))->member;
}

I remember it has something to do with GCC's typeof and using macros?

Upvotes: 38

Views: 55696

Answers (4)

FloatingRock
FloatingRock

Reputation: 7065

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); // 👈 check it out!

  printf("a=%d, b=%d \n", a, b); // a=0, b=3
  return 0;
}

Upvotes: 8

hugomg
hugomg

Reputation: 69964

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;
         ...
    }
}

Upvotes: 51

David X
David X

Reputation: 4176

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; \
    ... \
    })

Upvotes: 21

David Gelhar
David Gelhar

Reputation: 27900

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.

Upvotes: 4

Related Questions