Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

va_list with multiple types

Name: Anonymous 2010-07-24 1:23

i want to write soemthing like this:
a function which will print various types of arguments.
I tried to work with va_list, it doesn't work.
int main(){
write("this ",1.2," is ",'a',7," test");
}
should result in:
this 1.2 is a7 test

Name: Anonymous 2010-07-24 11:19

#include <stdio.h>
#include <stdarg.h>

struct idiot_object
{
  enum { INT, FLOAT, STR, CHAR } type;
  union
    {
        int i;
        char c;
        float f;
        char *s;
    } value;
};


void print(struct idiot_object *first, ...);
void print_idiot(struct idiot_object *);

void print_idiot(struct idiot_object *hi)
{
    switch(hi->type){
        case INT:   printf("%d", hi->value.i); break;
        case FLOAT: printf("%2.2f", hi->value.f); break;
        case STR:   printf("%s", hi->value.s); break;
        case CHAR:  printf("%c", hi->value.c); break;
        default:    puts("your an idiot"); break;
    }
}

void print(struct idiot_object *first, ...)
{
    va_list l;

    print_idiot(first);

    va_start(l, first);

    while((first = va_arg(l, struct idiot_object *)))
        print_idiot(first);

    va_end(l);
}

int main(void)
{
    struct idiot_object a = { .type = FLOAT, .value = { .f = 5.4 }},
                                            b = { .type = STR,   .value = { .s = "text" }},
                                            c = { .type = INT,   .value = { .i = 1 }},
                                            d = { .type = FLOAT, .value = { .f = 5e3 }},
                                            e = { .type = STR,   .value = { .s = "\n" }};


    print(&a, &b, &c, &d, &e, NULL);

    return 0;
}


tl;dr: OP you're an idiot.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List