Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable type as function parameter

Tags:

c

gcc

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?

like image 775
freonix Avatar asked Jul 12 '11 01:07

freonix


People also ask

Can you pass a type as a parameter in C?

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.

Can you pass a variable to a function?

In JavaScript, you cannot pass parameters by reference; that is, if you pass a variable to a function, its value is copied and handed to the function (pass by value). Therefore, the function can't change the variable. If you need to do so, you must wrap the value of the variable (e.g., in an array).

How do you pass a parameter to a variable?

If you want the called method to change the value of the argument, you must pass it by reference, using the ref or out keyword. You may also use the in keyword to pass a value parameter by reference to avoid the copy while guaranteeing that the value will not be changed. For simplicity, the following examples use ref .

How can you get the type of arguments passed to a function?

There are two ways to pass arguments to a function: by reference or by value. Modifying an argument that's passed by reference is reflected globally, but modifying an argument that's passed by value is reflected only inside the function.


1 Answers

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;          ...     } } 
like image 81
hugomg Avatar answered Oct 02 '22 03:10

hugomg