How to make a function use as many arguments as are given to it

1

Is there any way to make a function use multiple arguments without their declaration? For example:

#import<stdio.h>
#import"rlutil.h" //para as cores

void a(color,string){
    setColor(color);
    printf("%s",string);
    setColor(15); //Seleciona a cor Branca
}

I was wondering if there is a way to put

a(1,"Este",2,"E",8,"Um",4,"Exemplo");

without declaring cor1, string1, cor2, string2 , etc.
and that show the result

Este E Um Exemplo  

This is blue (1), And is green (2), One > Example in red (4)

    
asked by anonymous 26.03.2016 / 18:48

2 answers

1

To make a function use all the arguments that are given to it in C, it is necessary to use "..." when declaring the parameters. In the case of the example you presented I suggest preserving the function a () as it is:

void a(color c, string s) {
    setColor(c);
    printf("%s ",s);
    setColor(15); // o número 15 seleciona a cor branca
}

And use a new func () function that would get the variable length parameter list and call () every pair (color, string). It would look like this:

void func(int num, ...) {  // o inteiro é obrigatório, os três pontinhos 
                           // indicam que a quantidade de parâmetros será
                           // determinada em tempo de execução
    va_list valist; // estrutura que irá receber a lista de argumentos
    va_start(valist, num);  // macro que inicializa a lista de argumentos
    int i, cor;
    char * palavra;

    for ( i= 0; i < num; i=i+2 ) {
        cor = va_arg(valist, int);
        palavra = va_arg(valist, char *);
        a (cor, palavra);
    }

    va_end(valist); // limpa a memória reservada para valist
}

In case of this example your call would look like this:

func(8, 1,"Este",2,"É",8,"Um",4,"Exemplo");

reference .

    
03.04.2016 / 22:11
2

You can create this:

void a(int tamanho, ...) {
    va_list valist;
    va_start(valist, tamanho);
    for (int i = 0; i < tamanho; i += 2) {
        setColor(va_arg(valist, int));
        printf("%s", va_arg(valist, char *));
        setColor(15); //Seleciona a cor Branca
    }
    va_end(valist);
}

I do not remember if it's exactly this and I can not test it now, it probably has some errors, I think I've seen one :), but the idea is this.

Reference .

    
26.03.2016 / 20:04