File: stdarg.3

package info (click to toggle)
manpages-es 1.55-9
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 7,468 kB
  • ctags: 6
  • sloc: sh: 1,629; makefile: 64
file content (300 lines) | stat: -rw-r--r-- 8,106 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
.\" Copyright (c) 1990, 1991 The Regents of the University of California.
.\" All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\"    notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\"    notice, this list of conditions and the following disclaimer in the
.\"    documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\"    must display the following acknowledgement:
.\"	This product includes software developed by the University of
.\"	California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\"    may be used to endorse or promote products derived from this software
.\"    without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\"	@(#)stdarg.3	6.8 (Berkeley) 6/29/91
.\"
.\" Converted for Linux, Mon Nov 29 15:11:11 1993, faith@cs.unc.edu
.\" Additions, 2001-10-14, aeb
.\"
.\" Translation revised Tue Apr 18 2000 by Juan Piernas <piernas@ditec.um.es>
.\" Traducción revisada por Miguel Pérez Ibars <mpi79470@alu.um.es> el 3-febrero-2005
.\"
.TH STDARG 3  "14 octubre 2001" "" "Manual del Programador de Linux"
.SH NOMBRE
stdarg \- lista de argumentos variable
.SH SINOPSIS
.B #include <stdarg.h>
.sp
.BI "void va_start(va_list " ap ", " last );
.br
.BI "" type " va_arg(va_list " ap ", " type );
.br
.BI "void va_end(va_list " ap );
.br
.BI "void va_copy(va_list " dest ", va_list " src );
.SH 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)
.I stdarg.h
declara un tipo
.B 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.
.PP
Dicha función debe declarar un objeto de tipo
.B va_list
el cual es utilizado por las macros
.BR va_start ,
.BR va_arg
y
.BR va_end .
.SS va_start
La macro
.B va_start
inicializa
.I ap
para su uso posterior por
.B va_arg
y
.BR va_end ,
y debe ser llamada en primer lugar.
.PP
El parámetro
.I last
es el nombre del último parámetro antes de la lista de argumentos variables,
es decir, el último parametro sobre el cual la función llamada conoce el
tipo.
.PP
Dado que la dirección de este parámetro puede ser utilizada por la macro
.B va_start
no debería ser declarado como una variable de registro, como una función ni
como un array.
.PP
.SS va_arg
La macro
.B va_arg
expande una expresión que contiene el tipo y el valor del próximo argumento
empleado en la llamada. El parámetro
.I ap
es el 
.BI va_list
.I ap
inicializado por
.BR va_start .
Cada llamada a
.B va_arg
modifica
.I ap
por tanto la siguiente llamada devolverá el próximo argumento. El parámetro
.I type
es el nombre de un tipo especificado para que para que el tipo de un puntero
a un objeto que es de dicho tipo pueda ser obtenido simplemente añadiendo un
* a
.IR type .
.PP
El primer uso de la macro
.B va_arg
despues de
.B va_start
devuelve el argumento tras
.IR last .
Invocaciones sucesivas devolverán los valores del resto de los argumentos.
.PP
Si no hay próximo argumento, o si
.I type
no es compatible con el tipo del próximo argumento, se producirán errores
impredecibles.
.PP
Si
.I ap
es pasado a una función que usa
.BI va_arg( ap , type ),
el valor de
.I ap
es indefinido al regresar dicha función.
.SS va_end
A cada invocación de
.B va_start
le corresponde una invocación de
.B va_end
en la misma función. Después de la llamada a
.BI va_end( ap )
la variable
.I ap
es indefinida. Son posibles varios recorridos de la lista,
cada uno comprendido entre
.B va_start
y
.B va_end.
.B va_end
puede ser una macro o una función.
.SS va_copy
.\" Proposal from clive@demon.net, 1997-02-28
Una implementación obvia haría que 
.B 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
.RS
.nf
	va_list aq = ap;
.fi
.RE
Desafortunadamente, también hay sistemas que lo
implementan como un array de punteros (de longitud 1), 
y por tanto es necesario
.RS
.nf
	va_list aq;
	*aq = *ap;
.fi
.RE
Finalmente, en sistemas donde los parámetros son pasados en registros,
puede ser necesario para
.B va_start
reservar memoria y almacenar ahí los parámetros junto con
una indicación de qué parámetro es el siguiente, con el fin
de que
.B va_arg
pueda recorrer la lista. Ahora
.B va_end
puede liberar de nuevo la memoria reservada.
Para acomodarse a esta situación, C99 añade una macro
.BR va_copy ,
para que la asignación de arriba puede reemplazarse por
.RS
.nf
	va_list aq;
	va_copy(aq, ap);
	...
	va_end(aq);
.fi
.RE
A cada invocación de
.B va_copy
le corresponde una invocación de 
.B va_end
en la misma función.
Algunos sistemas que no proporcionan
.B va_copy
tienen
.B __va_copy
en su lugar, puesto que ese fue el nombre usado en la propuesta inicial.
.SH EJEMPLOS
La función
.I foo
toma una cadena de caracteres de formato e imprime el argumento asociado
con cada caracter de formato basado en el tipo.
.RS
.nf
#include <stdio.h>
#include <stdarg.h>

void foo(char *fmt, ...) {
	va_list ap;
	int d;
	char c, *p, *s;

	va_start(ap, fmt);
	while (*fmt)
		switch(*fmt++) {
		case 's':			/* string */
			s = va_arg(ap, char *);
			printf("string %s\en", s);
			break;
		case 'd':			/* int */
			d = va_arg(ap, int);
			printf("int %d\en", d);
			break;
		case 'c':			/* char */
			/* Aquí es necesaria una conversión forzada
			 * de tipos ya que va_arg sólo toma tipos
			 * totalmente `ascendidos'.
			 */
			c = (char) va_arg(ap, char);
			printf("char %c\en", c);
			break;
		}
	va_end(ap);
}
.fi
.RE
.SH "CONFORME A"
Las macros
.BR va_start ,
.BR va_arg
y
.B va_end
concuerdan con ANSI X3.159-1989 (``C89'').
C99 define la macro
.B va_copy.
.SH COMPATIBILIDAD
Estas macros
.I no
son compatibles con las macros históricas que reemplazan. Se puede encontrar
una versión compatible "hacia atrás" en el fichero de cabecera
.IR varargs.h .
.SH COMPARACIÓN
La configuración histórica es:
.RS
.nf
#include <varargs.h>

void foo(va_alist) va_dcl {
	va_list ap;

	va_start(ap);
	while(...) {
		...
		x = va_arg(ap, type);
		...
	}
	va_end(ap);
}
.fi
.RE
En algunos sistemas,
.I va_end
contiene un carácter de cierre '}' que se
corresponde con un '{' en
.IR va_start ,
con lo que ambas macros deben aparecer en la misma función, y de 
una manera que lo permita.
.SH FALLOS
Al contrario que las macros
.BR varargs ,
las macros
.B stdarg
no permiten a los programadores codificar una función con argumentos
variables. Este problema genera trabajo principalmente cuando se convierte
código basado en
.B varargs
a
.B stdarg
pero además crea dificultades a las funciones que quieran pasar todos sus
argumentos en una función que toma una lista de argumentos
.BR va_list ,
como
.BR vfprintf (3).