On the realization of variable parameter function from printf

Source: Internet
Author: User
Tags printf

I've always felt that printf seems to be one of the most powerful functions in the C language library, not only because it can format output, but because it has no limits on the number of parameters, and a few to give. printf's strong adaptability to parameter numbers and parameter types gives rise to a strong interest in exploring it.

1. Use case

int a =10;
double b = 20.0;
char *str = "Hello world";
printf("begin print\n");
printf("a=%d, b=%.3f, str=%s\n", a, b, str);
...

From the use of printf, it is not hard to find a rule that the first argument to printf is always a string, regardless of the number of variable arguments. And it is this first parameter that makes it possible to confirm how many trailing parameters are left behind. The amount of stack space used for each trailing parameter is determined by the first format string. However, how does printf get the value of the parameter after the first argument, see the following code

Implementation of 2.printf function

//acenv.h
typedef char *va_list;
#define _AUPBND    (sizeof (acpi_native_int) - 1)
#define _ADNBND    (sizeof (acpi_native_int) - 1)

#define _bnd(X, bnd)  (((sizeof (X)) + (bnd)) & (~(bnd)))
#define va_arg(ap, T)  (*(T *)(((ap) += (_bnd (T, _AUPBND))) - (_bnd (T,_ADNBND))))
#define va_end(ap)   (void) 0
#define va_start(ap, A) (void) ((ap) = (((char *) &(A)) + (_bnd (A,_AUPBND))))
//start.c
static char sprint_buf[1024];
int printf(char *fmt, ...)
{
  va_list args;
  int n;
  va_start(args, fmt);
  n = vsprintf(sprint_buf, fmt, args);
  va_end(args);
  write(stdout, sprint_buf, n);
  return n;
}
//unistd.h
static inline long write(int fd, const char *buf, off_t count)
{
  return sys_write(fd, buf, count);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.