C variadic function: How to specify which type to give to va_arg

不羁岁月 提交于 2019-12-04 10:25:25

Types are not first-class citizens in C.

But there are not that many types you have to care about: you can safely cast from unsigned to signed and the other way around, same goes for char* and void*, so for a basic printf, you have to handle:

  • char
  • short
  • int
  • long
  • float
  • double
  • void*

union to the rescue !

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:
            /* ... */
    }
}

Then you just have to create a lookup table, storing both a function pointer and a t_type for each valid format specifier.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!