Scroll to navigation

STDARG(3) Manual del Programador de Linux STDARG(3)

NOMBRE

stdarg, va_start, va_arg, va_end, va_copy - lista de argumentos variable

SINOPSIS

#include <stdarg.h>

void va_start(va_list ap, last);
type va_arg(va_list ap, type);
void va_end(va_list ap);
void va_copy(va_list dest, va_list src);

DESCRIPCIÓN

Una función podría ser llamada con un número de argumentos variable de tipos igualmente variables. El fichero de cabecera (include) <stdarg.h> declara un tipo va_list y define tres macros para moverse a través de una lista de argumentos cuyo número y tipo no son conocidos para la función llamada.

Dicha función debe declarar un objeto de tipo va_list el cual es utilizado por las macros va_start(), va_arg() y va_end().

va_start()

La macro va_start() inicializa ap para su uso posterior por va_arg() y va_end(), y debe ser llamada en primer lugar.

The argument last is the name of the last argument before the variable argument list, that is, the last argument of which the calling function knows the type.

Because the address of this argument may be used in the va_start() macro, it should not be declared as a register variable, or as a function or an array type.

va_arg()

The va_arg() macro expands to an expression that has the type and value of the next argument in the call. The argument ap is the va_list ap initialized by va_start(). Each call to va_arg() modifies ap so that the next call returns the next argument. The argument type is a type name specified so that the type of a pointer to an object that has the specified type can be obtained simply by adding a * to type.

El primer uso de la macro va_arg() despues de va_start() devuelve el argumento tras last. Invocaciones sucesivas devolverán los valores del resto de los argumentos.

Si no hay próximo argumento, o si type no es compatible con el tipo del próximo argumento, se producirán errores impredecibles.

Si ap es pasado a una función que usa va_arg(ap,type), el valor de ap es indefinido al regresar dicha función.

va_end()

A cada invocación de va_start() le corresponde una invocación de va_end() en la misma función. Después de la llamada a va_end(ap) la variable ap es indefinida. Son posibles varios recorridos de la lista, cada uno comprendido entre va_start() y va_end(). va_end() puede ser una macro o una función.

va_copy()

The va_copy() macro copies the (previously initialized) variable argument list src to dest. The behavior is as if va_start() were applied to dest with the same last argument, followed by the same number of va_arg() invocations that was used to reach the current state of src.

Una implementación obvia haría que va_list fuera un puntero al marco de pila de la función. En tal caso (con mucho el más común) no hay ningún problema con una asignación del tipo


va_list aq = ap;

Desafortunadamente, también hay sistemas que lo implementan como un array de punteros (de longitud 1), y por tanto es necesario


va_list aq;
*aq = *ap;

Finally, on systems where arguments are passed in registers, it may be necessary for va_start() to allocate memory, store the arguments there, and also an indication of which argument is next, so that va_arg() can step through the list. Now va_end() can free the allocated memory again. To accommodate this situation, C99 adds a macro va_copy(), so that the above assignment can be replaced by


va_list aq;
va_copy(aq, ap);
...
va_end(aq);

A cada invocación de va_copy() le corresponde una invocación de va_end() en la misma función. Algunos sistemas que no proporcionan va_copy() tienen __va_copy() en su lugar, puesto que ese fue el nombre usado en la propuesta inicial.

ATRIBUTOS

Para obtener una explicación de los términos usados en esta sección, véase attributes(7).

Interfaz Atributo Valor
va_start(), va_end(), va_copy() Seguridad del hilo Multi-hilo seguro
va_arg() Seguridad del hilo MT-Safe race:ap

CONFORME A

Las macros va_start(), va_arg() y va_end() concuerdan con C89. C99 define la macro va_copy().

ERRORES

Unlike the historical varargs macros, the stdarg macros do not permit programmers to code a function with no fixed arguments. This problem generates work mainly when converting varargs code to stdarg code, but it also creates difficulties for variadic functions that wish to pass all of their arguments on to a function that takes a va_list argument, such as vfprintf(3).

EJEMPLOS

La función foo toma una cadena de caracteres de formato e imprime el argumento asociado con cada caracter de formato basado en el tipo.

#include <stdio.h>
#include <stdarg.h>
void
foo(char *fmt, ...)   /* '...' is C syntax for a variadic function */
{

va_list ap;
int d;
char c;
char *s;
va_start(ap, fmt);
while (*fmt)
switch (*fmt++) {
case 's': /* string */
s = va_arg(ap, char *);
printf("string %s\n", s);
break;
case 'd': /* int */
d = va_arg(ap, int);
printf("int %d\n", d);
break;
case 'c': /* char */
/* need a cast here since va_arg only
takes fully promoted types */
c = (char) va_arg(ap, int);
printf("char %c\n", c);
break;
}
va_end(ap); }

VÉASE TAMBIÉN

vprintf(3), vscanf(3), vsyslog(3)

COLOFÓN

Esta página es parte de la versión 5.10 del proyecto Linux man-pages. Puede encontrar una descripción del proyecto, información sobre cómo informar errores y la última versión de esta página en https://www.kernel.org/doc/man-pages/.

TRADUCCIÓN

La traducción al español de esta página del manual fue creada por Juan Piernas <piernas@ditec.um.es> y Miguel Pérez Ibars <mpi79470@alu.um.es>

Esta traducción es documentación libre; lea la GNU General Public License Version 3 o posterior con respecto a las condiciones de copyright. No existe NINGUNA RESPONSABILIDAD.

Si encuentra algún error en la traducción de esta página del manual, envíe un correo electrónico a debian-l10n-spanish@lists.debian.org>..

1 Noviembre 2020