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

喜夏-厌秋 提交于 2019-12-25 19:04:11

问题


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


回答1:


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




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



回答3:


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.



来源:https://stackoverflow.com/questions/23103875/how-can-printf-function-can-take-variable-parameters-in-number-while-output-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!