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

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

  •  04-07-2023
  •  | 
  •  

문제

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

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top