C variadic function: how to specify the type to be assigned to va_arg

In a function like printf, we use stdarg.hto process variable parameters.

void print(int args,...){
    va_list ap;
    va_start(ap, args);
    int i = 0;
    for(i=0; i<args; i++){
        printf("%d\n",va_arg(ap, int));
    }
    va_end(ap);
}

We want to parse the list of formats (the first argument provided to our variational function) to track the types of arguments specified in the list of formats, then call va_arg with the appropriate type.

I am doing the first loop to parse the list of formats, storing the letters of the qualifiers in an array. So I know what type we expect and how much there.

ex: ft_like_printf("Watch your %d %s\n", 6, "Spider pig");

specifiers_list = "ds" So d <=> int and s <=> char * (same qualifiers as printf)

But how to encode it dynamically ? What is the syntax for calling va_arg with different types?

THAT, , , , , ? , ? , enum + union struct, union + function?

, :

typedef struct s_flist
{
    char c;
    (*f)();
}              t_flist;

t_flist flist[] = 
    {
        { 's',  &putstr  },
        { 'i',  &put_number },
        { 'd',  &put_number }
    };
+4
1

C.

, : unsigned signed, , char* void*, printf, :

  • char
  • *

union !

typedef union
{
    char as_char;
    short as_short;
    int as_int;
    long as_long;
    float as_float;
    double as_double;
    void* as_ptr;
} t_value;

typedef enum {
    CHAR_T,
    INT_T,
    /* It goes on */
    ...
} t_type;

t_value get_value(va_list ap, t_type type) {
    /* You can't avoid this step, there is no way to iterate over types */
    switch (type) {
        case T_CHAR:
            return va_arg(ap, char);
        case T_INT:
            /* ... */
    }
}

, , t_type .

+1

All Articles