36

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?

freonix
  • 1,605
  • 3
  • 22
  • 35

4 Answers4

49

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;
         ...
    }
}
hugomg
  • 68,213
  • 24
  • 160
  • 246
  • Hi hugomg, I'm sorry but I don't understand the alternative. Could you elaborate a little? Thanks :-) –  Mar 19 '16 at 10:30
  • 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. – hugomg Mar 19 '16 at 13:04
  • for me it's work only with typedef: "typedef enum { CHAR, INT, FLOAT, DOUBLE } TYPE;" – ChaosPredictor May 12 '17 at 18:50
20

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; \
    ... \
    })
David X
  • 3,998
  • 3
  • 29
  • 32
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;
}
FloatingRock
  • 6,741
  • 6
  • 42
  • 75
  • 3
    You don't actually pass a type to a function here, but create new code for every time you use it. – handras Nov 27 '20 at 16:14
  • 1
    To avoid doubt: `({...})` is a "statement expression", which is a GCC extension and not standard C. – Ed. Feb 07 '22 at 20:17
3

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.

David Gelhar
  • 27,873
  • 3
  • 67
  • 84
  • 17
    Dont be so negative have a more can do attitude ;) – Ray Garner Jan 17 '17 at 06:43
  • It is possible with quite extensive C macros - see this very short type-generic thing in Boost PP (https://www.boost.org/doc/libs/1_78_0/libs/preprocessor/doc/examples/array_arithmetic.c) or the Perl Data Language (https://metacpan.org/pod/PDL - disclosure: I am current maintainer of this 26-year-old project). – Ed. Feb 07 '22 at 20:19