How to make a function use how many arguments are provided to it

Asked

Viewed 287 times

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’s a way to put

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

undeclared cor1, string1, cor2, string2, etc..
and show the result

Este E Um Exemplo  

in which This turn blue(1), And turn green(2), A is grey(8) and Example stay in red(4)

2 answers

2


To make a function use as many arguments as are provided 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 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 function func() that would receive the list of parameters of variable size and call() each 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 the case of this example your call would look like this:

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

Ference (in English).

2

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 put in the Github for future reference.

I don’t remember if this is exactly it and I can’t test it now, there are probably some mistakes, I think I’ve seen one :), but the idea is this.

Reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.