Use stdarg. h to implement simple printf (variable length parameter), stdarg. hprintf

Source: Internet
Author: User

Use stdarg. h to implement simple printf (variable length parameter), stdarg. hprintf

This mainly enables stdarg. h to support variable parameters.

The key steps are as follows:

1. Define a va_list variable ap.

2. initialize the ap so that it points to the first parameter in the variable parameter table.

3. Use va_arg to obtain the value of the specified type.

4. Call va_end to disable the ap pointer.


The Code is as follows:

# Include <stdio. h> # include <stdarg. h> void testprintf (char * fmt ,...) {va_list ap;/* points to each unnamed arg in turn */char * p, * sval; int ival; double dval; va_start (ap, fmt ); /* make ap point to 1st unnamed arg */for (p = fmt; * p; p ++) {if (* p! = '%') {Putchar (* p); continue;} switch (* ++ p) {case 'D': ival = va_arg (ap, int ); printf ("% d", ival); break; case 'F': dval = va_arg (ap, double); printf ("% f", dval); break; case's ': for (sval = va_arg (ap, char *); * sval; sval ++) putchar (* sval); break; default: putchar (* p ); break ;}} va_end (ap);/* clean up when done */} int main () {minprintf ("haha % s", "12345"); return 0 ;}


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.