variable number of arguments in ANSI C
Doug Gwyn
gwyn at smoke.BRL.MIL
Thu Jun 22 07:34:24 AEST 1989
In article <20070 at adm.BRL.MIL> NYMAN at intellicorp.com (Lars Nyman) writes:
!What assumptions is OK to make about variable number of arguments in ANSI C ?
This discussion should be conducted in comp.lang.c or perhaps comp.std.c,
not in a UNIX newsgroup, so I've directed follow-ups to comp.lang.c
(INFO-C on the Internet).
!#include <stdarg.h>
!void foo(int i, ...)
!{
! va_list args;
! va_start(args, i); /* initialize args pointer */
! va_arg(args, char *); /* pop the first argument */
! bar(i - 1, args); /* let bar() see the rest, Q1 */
*** ERROR *** "va_end(args);" needed here
! va_start(args, i); /* initialize args pointer again, Q2 */
! baz(i, args); /* let baz() see them all, Q1 */
! va_end(args); /* done */
!}
!void bar(int i, va_list args)
!{
! while (i > 0) {
! printf("%s\n", va_arg(args, char *)); /* pop arguments, Q1 */
*** ERROR *** printf() requires prior inclusion of <stdio.h>
! i--;
! }
!}
!void baz(int i, va_list args)
!{
! while (i > 0) {
! printf("%s\n", va_arg(args, char *)); /* pop arguments, Q1 */
! i--;
! }
!}
!main()
!{
! foo(3, "Monday", "Tuesday", "Wednesday");
*** ERROR *** main() fails to return a value
!}
!I know this will work in atleast some implementations of ANSI C, but is it
!portable, legal ANSI C code ?
Except for the ERRORs I flagged above, it is strictly conforming.
!Q1: Is it OK to pass the va_list to another function and let that function pop
! all or some of the arguments with va_arg() ?
Yes, va_list objects are designed to be passable as function parameters.
However, upon return from the function they are "dead" and must not be
used to access additional arguments before the va_end().
!Q2: Is it OK to "restart" by calling va_start() more than once ?
Yes.
More information about the Comp.lang.c
mailing list