-1

I really wonder how printf executed. Is there a parameter array structure in C? Can i define my custom function like printf?

Phylogenesis
  • 7,775
  • 19
  • 27
Tarık Özgün Güner
  • 1,051
  • 10
  • 10
  • 2
    Read about [`va_start`](http://en.cppreference.com/w/cpp/utility/variadic/va_start), [`va_arg`](http://en.cppreference.com/w/cpp/utility/variadic/va_arg) and [`va_end`](http://en.cppreference.com/w/cpp/utility/variadic/va_end). While that reference documentation is using the C++ ``, change the header file to `` and you're good to go. – Some programmer dude Apr 16 '14 at 08:26
  • Check this answer too http://stackoverflow.com/questions/4867229/code-for-printf-function-in-c – Suvarna Pattayil Apr 16 '14 at 08:27
  • http://en.wikipedia.org/wiki/Variadic_function – Vladimir Apr 16 '14 at 08:27
  • You are talking about `varargs`. Another question deals with this: http://stackoverflow.com/questions/15784729/an-example-of-use-of-varargs-in-c – Phylogenesis Apr 16 '14 at 08:28
  • But then those 'articles' do not explain how it works, only how it's implemented. – Sebastian Mach Apr 16 '14 at 08:28
  • Too bad. It was my understanding you were looking for an answer to "I really wonder how printf executed.", not "How can I _use_ it myself" – Sebastian Mach Apr 16 '14 at 08:55
  • possible duplicate of [C/C++: Passing variable number of arguments around](http://stackoverflow.com/questions/205529/c-c-passing-variable-number-of-arguments-around) – Sebastian Mach Apr 16 '14 at 09:34

3 Answers3

2

A special type va_list is used for using variable list arguements. read this.

LearningC
  • 3,182
  • 1
  • 12
  • 19
2

You could use the va_arg macro. Here's an example

#include <stdio.h>      /* printf */
#include <stdarg.h>     /* va_list, va_start, va_arg, va_end */

int FindMax (int n, ...)
{
  int i,val,largest;
  va_list vl;
  va_start(vl,n);
  largest=va_arg(vl,int);
  for (i=1;i<n;i++)
  {
    val=va_arg(vl,int);
    largest=(largest>val)?largest:val;
  }
  va_end(vl);
  return largest;
}

int main ()
{
  int m;
  m= FindMax (7,702,422,631,834,892,104,772);
  printf ("The largest value is: %d\n",m);
  return 0;
}
Giovanni
  • 1,313
  • 1
  • 10
  • 14
1

A program conforms to some specific ABI and the calling convention is defined by the abi.

A calling convention defines how parameters passed to a function, usually stored either in registers or/and on the stack.The function then retrieves the parameters accordingly and this is also for variadic functions.

Sure you can define variadic function yourself.

tristan
  • 4,235
  • 2
  • 21
  • 45