Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Length Arguments without using stdarg.h

Tags:

c

printf

I'm trying to understand and implement a way to handle variable length argument function by checking the stack, but I have not idea on where and how to start. I have found the following links helpful but I still don't quite understand how I would be able to something like this in c for something like a print function.

http://www.swig.org/Doc1.3/Varargs.html

Trailing dots (...) within function argument list in C++

like image 806
Morki Avatar asked Dec 11 '25 07:12

Morki


1 Answers

Look in the C Reference Manual by Dennis M. Ritchie at the implementation of printf() that existed long before ... and <stdarg.h>:

printf ( fmt, args )
  char fmt [ ] ;
{
  ...
  int *ap, x, c ;
  ap = &args ; /* argument pointer */
  ...
  for ( ; ; ) {
    while ( ( c = *fmt++ ) != ´%´ ) {
      ...
      switch ( c = *fmt++) {
      /* decimal */
      case ´d ´:
        x = *ap++ ;
        if(x < 0) {
          x = -x;
          if ( x<0 ) { /* is - infinity */
            printf ( "-32768" ) ;
            continue ;
          }
          putchar ( ´-´);
        }
        printd(x);
        continue ;
      ...
      }
      ...
    }
    ...
  }
}

printd(n)
{
  int a ;
  if ( a=n/10 )
    printd(a);
  putchar ( n%10 + ´0´ ) ;
}

You can disregard the old (AKA K&R) syntax of function and parameter declaration:

printf ( fmt, args )
  char fmt [ ] ;

and even replace it with a more modern:

int printf ( char fmt[], int args )

but the idea is the same, you get a pointer to the first optional argument (args) directly, as is done in the above code with ap = &args;, and then keep incrementing it to get access to further arguments.

Or you can do it indirectly, using the last non-optional argument as the starting point:

int printf ( char fmt[], ... )
{
  ...
  int *ap, x, c ;
  ap = &fmt ; /* argument pointer */
  ap++; /* ap now points to first optional argument */
  ...
}

This illustrates the mechanism.

Beware, if you write your code like this, it won't be portable and it may even fail work with your compiler.

like image 197
Alexey Frunze Avatar answered Dec 14 '25 10:12

Alexey Frunze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!