Stdarg.h

Stdarg.h

is a header in the C standard library of the C programming language that allows functions to accept an indefinite number of arguments. C++ provides this functionality in the header ; the C header, though permitted, is deprecated in C++.

The contents of are typically used in variadic functions, though they may be used in other functions (for example, vprintf) called by variadic functions.

Declaring variadic functions

Variadic functions are functions which may take a variable number of arguments and are declared with an ellipsis in place of the last parameter. An example of such a function is printf. A typical declaration is

int check(int a, double b, ...);

Variadic functions must have at least one named parameter, so, for instance,

char *wrong(...);

is not allowed in C. (In C++, such a declaration is permitted, but not very useful.) In C, a comma must precede the ellipsis; in C++, it is optional.

Defining variadic functions

The same syntax is used in a definition:

long func(char, double, int, ...);

long func(char a, double b, int c, ...){ /* ... */}

An ellipsis may also appear in old-style function definitions:

long func();

long func(a, b, c, ...) char a; double b;{ /* ... */}

tdarg.h types

tdarg.h macros

Accessing the arguments

To access the unnamed arguments, one must declare a variable of type va_list in the variadic function. The macro va_start is then called with two arguments: the first is the va_list, the second is the name of the last named parameter of the function. After this, each invocation of the va_arg macro yields the next argument. The first argument to va_arg is the va_list and the second is the type of the next argument passed to the function. Finally, the va_end macro must be called on the va_list before the function returns. (It is not required to read in all the arguments.)

C99 provides an additional macro, va_copy, which can duplicate the state of a va_list. The macro invocation va_copy(va2, va1) copies va1 into va2.

There is no mechanism defined for determining the number or types of the unnamed arguments passed to the function. The function is simply required to know or determine this somehow, the means of which vary. Common conventions include:
* Use of a printf or scanf-like format string with embedded specifiers that indicate argument types.
* A sentinel value at the end of the variadic arguments.
* A count argument indicating the number of variadic arguments.

Type safety

Some C implementations, such as GCC, provide C extensions that allow the compiler to check for the proper use of format strings and sentinels. Barring these extensions, the compiler usually cannot check whether the unnamed arguments passed are of the type the function expects. Therefore, care should be taken to ensure correctness in this regard, since undefined behavior results if the types do not match. For example, if passing a null pointer, one should not write simply NULL but cast to the appropriate pointer type. Another consideration is the default argument promotions applied to the unnamed arguments. A float will automatically be promoted to a double. Likewise, arguments of types narrower than an int will be promoted to int or unsigned int. The function receiving the unnamed arguments must expect the promoted type.

Example


#include
#include

void printargs(int arg1, ...) /*print all int type args, finishing with -1 */{ va_list ap; int i;

va_start(ap, arg1); for (i = arg1; i != -1; i = va_arg(ap, int)) printf("%d ", i); va_end(ap); putchar(' ');}

int main(void){ printargs(5, 2, 14, 84, 97, 15, 24, 48, -1); printargs(84, 51, -1); printargs(-1); printargs(1, -1); return 0;}

This program yields the output:

5 2 14 84 97 15 24 48 84 51

1

POSIX defines the legacy header , which dates from before the standardization of C and provides functionality similar to . This header is not part of ISO C. The file, as defined in the second version of the Single Unix Specification, simply contains all of the functionality of C89 stdarg.h, with the exceptions that:

* it cannot be used in Standard C new-style definitions
* you may choose not to have a given argument (Standard C requires at least one argument)
* the way it works is different:

In Standard C, one would write


#include

int summate(int n, ...){ va_list ap; int i = 0;

va_start(ap, n); for (; n; n--) i += va_arg(ap, int); va_end(ap); return i;}

or with old-style function definitions:


#include

int summate(n, ...) int n;{ /* ... */}

and call with

summate(0); summate(1, 2); summate(4, 9, 2, 3, 2);

With , the function would be:


#include

summate(n, va_alist) va_dcl /* no semicolon here! */{ va_list ap; int i = 0;

va_start(ap); for (; n; n--) i += va_arg(ap, int); va_end(ap); return i;}

and is called the same way.

requires old-style function definitions because of the way the implementation works. [cite web|url=http://www.opengroup.org/onlinepubs/007908799/xsh/varargs.h.html|title=<varargs.h>|accessdate=1-8-2007]

References

[http://www.opengroup.org/onlinepubs/009695399/basedefs/stdarg.h.html IEEE Std 1003.1 stdarg.h]


Wikimedia Foundation. 2010.

Look at other dictionaries:

  • stdarg.h — Стандартная библиотека языка программирования С assert.h complex.h ctype.h errno.h fenv.h float.h inttypes.h iso646.h limits.h locale.h math.h setjmp.h signal.h stdarg.h stdbool.h stddef.h …   Википедия

  • Standard C Library — Die Standard C Library ist eine genormte Funktionsbibliothek für die Programmiersprache C, die etwa 200 häufig benötigte Funktionen für Ein und Ausgabe, mathematische Operationen, Verarbeitung von Zeichenketten, Speicherverwaltung und andere… …   Deutsch Wikipedia

  • Fonction variadique — En programmation informatique, une fonction variadique est une fonction d arité indéfinie, c est à dire qui accepte un nombre variable de paramètres. De nombreuses opérations mathématiques et logiques peuvent se représenter sous forme de… …   Wikipédia en Français

  • C standard library — The C Standard Library consists of a set of sections of the ANSI C standard in the programming language C. They describe a collection of headers and library routines used to implement common operations such as input/output[1] and string handling …   Wikipedia

  • Variadic function — In computer programming, a variadic function is a function of variable arity; that is, one which can take different numbers of arguments. Support for variadic functions differs widely among programming languages.There are many mathematical and… …   Wikipedia

  • Funciones de la biblioteca estándar de C — Anexo:Funciones de la biblioteca estándar de C Saltar a navegación, búsqueda El propósito de este artículo es proporcionar un listado alfabético de todas las funciones de la biblioteca estándar de C, y unas pocas funciones no estándar. Contenido… …   Wikipedia Español

  • Стандартная библиотека языка Си — Стандартная библиотека языка программирования С assert.h complex.h ctype.h errno.h fenv.h float.h inttypes.h iso646.h limits.h locale.h math.h setjmp.h signal.h stdarg.h stdbool.h stddef.h …   Википедия

  • Anexo:Funciones de la biblioteca estándar de C — El propósito de este artículo es proporcionar un listado alfabético de todas las funciones de la biblioteca estándar de C, y unas pocas funciones no estándar. Contenido 1 assert.h 2 ctype.h 3 errno.h 4 float.h …   Wikipedia Español

  • Standard Template Library — C++ Standard Library fstream iomanip ios iostream sstream string …   Wikipedia

  • C file input/output — C Standard Library Data types Character classification Strings Mathematics File input/output Date/time Localiza …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”