Little problem with C

I want to implement a function with a variable number of arguments. This function allows me to call another function using a list of optional arguments. The purpose of this function is to call any function depending on certain conditions (depending on the functions being called, if the first two arguments are equal, we call the function). My problem is that the functions that can be called do not have the same number of arguments and therefore I do not know how to pass arguments every time I have another function

For example, if I have this:

void func(int value_to_compare, int compared_value, int arg_number, char *arg_types, char *function_name, ...)

I can call it this:

char arg1;
int arg2, arg3;
int condition1;

func(condition1, 1, 1, "c", func1, arg1);
func(condition1, 0, 2, "ci", func2, arg1, arg2);
func(arg2, 0 , 3, "cii", func3, arg1, arg2, arg3);

and called functions:

func1(char);
func2(char, int);
func3(char, int, int);

I am trying to explain more if I have, for example:

struct element_list {
char *element_type;
char *element_name;
}

, , , "func" , , , -

func(element_list.element_type, "CHAR", func1, "s", element_list.element_name);

, - , .

+3
3

,

void func(int value_type, void *value_to_compare, void *compared_value, char *arg_types, void (*function_name)(), ...)

value_type, , value_to_compare compare_value, , , , , function function_name. , arg_types, - , :

switch(strlen(arg_types)) {
case 0:
function_name();
break;
case 1:
function_name(args[0]);
break;
case 2:
function_name(args[0], args[1]);
break;
...
}

args

void* args[MAX_NUMBER_ARGS];

args arg_types, , ...

0

, . , C.

:

: typedef void my_func_type(void*) "" .

- , . , ... , ​​. , ...


, # 1

, , func,

char arg1;
int arg2, arg3;
int condition1;

func(condition1, 1, 1, "c", func1, arg1);
func(condition1, 0, 2, "ci", func2, arg1, arg2);
func(arg2, 0 , 3, "cii", func3, arg1, arg2, arg3);

:

if (condition1 == 1) func1(arg1);
if (condition1 == 0) func2(arg1, arg2);
if (arg2 == 0)       func3(arg1, arg2, arg3);

... - .: -)

, , - . : . ... , ++ (, , , bind ).

C ++, , ... , , . - , if? - .

+4

. struct, , . struct ( /).

The second option is to format the arguments so that they can be read with va_start, va_argand va_end. To use this, you will need to find out the type of the next argument, so you will need to pass it as input. You should also know in advance when the last argument is reached, so you need to pass this as input. It works the same way printf, and why you need to pass the format string to printf.

+1
source

All Articles