How can printf function can take variable parameters in number while output them?

StackOverflow https://stackoverflow.com/questions/23103875

  •  04-07-2023
  •  | 
  •  

Pergunta

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

Foi útil?

Solução

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

Outras dicas

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;
}

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top