38

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?

1
  • 7
    Not in standard C. Maybe in GCC, if you are (un)lucky. Commented Jul 12, 2011 at 1:31

4 Answers 4

51

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;
         ...
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi hugomg, I'm sorry but I don't understand the alternative. Could you elaborate a little? Thanks :-)
I just realized that the alternative doesn't really work as written... so I deleted it. But the basic idea I originally had was to code things in "object oriented" style and use subtype polymorphism to do the branching instead of a switch statement.
for me it's work only with typedef: "typedef enum { CHAR, INT, FLOAT, DOUBLE } TYPE;"
21

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

Comments

8

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

2 Comments

You don't actually pass a type to a function here, but create new code for every time you use it.
To avoid doubt: ({...}) is a "statement expression", which is a GCC extension and not standard C.
4

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.

2 Comments

Dont be so negative have a more can do attitude ;)
It is possible with quite extensive C macros - see this very short type-generic thing in Boost PP (boost.org/doc/libs/1_78_0/libs/preprocessor/doc/examples/…) or the Perl Data Language (metacpan.org/pod/PDL - disclosure: I am current maintainer of this 26-year-old project).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.