delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1993/08/20/04:28:12

Date: Fri, 20 Aug 1993 10:02:42 +0200 (MET DST)
From: Harco de Hilster <harcoh AT cs DOT kun DOT nl>
To: djgpp AT sun DOT soe DOT clarkson DOT edu (DJGPP), Mark Bergman <bergman AT panix DOT com>
Subject: Re: varargs

Excerpts from external.djgpp: 20-Aug-93 varargs by Mark Bergman AT panix DOT com 
> Does anyone have some good examples of code using variable
> argument lists <varargs.h>?

I had some trouble using varargs.h, but the following code works with
<stdarg.h>:

#include <stdarg.h>

char bigbuf[256];

void Printf(char *fmt, ...)
{ va_list args;

  va_start(args, fmt);
  vsprintf(bigbuf, fmt, args);
  va_end(args);

  puts(bigbuf);
}

This works fine because vsprintf knows how many args it should expect
from the format string. If you want to do something with the args your
self, you need va_arg(args, some type) in a loop and terminate the args
with e.g. NULL.
(off hand!):

void put_strings(char *first, ...)
{ va_list args;

  va_start(args, first);
  while(1)
  { char *s = va_arg(args, (char *)); // increments to next arg
    if (s == NULL)
        break;
    puts(s);
  }
  va_end(args);
}

put_strings("hello", "world", NULL);

This implies that you have to know the type of the args.

You can't nest calls that use va_start/va_end, but the librairy
'varargs' functions (like vsprintf) don't use varargs.

Hope this helps,

Harco.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019