The function of variable length parameter

Source: Internet
Author: User

A small example of a function with variable length parameters in C language:

#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
static int pp;
void func1()
{
    static int pp1;
    printf("hello world\n");
}

void tiny_printf(char *format, ...)
{
    int i;
    va_list ap;
    va_start(ap, format);
    for (i = 0; format[i] != ‘\0‘; ++i)
    {
        switch (format[i])
        {
        case ‘s‘:
            printf("%s ", va_arg(ap, char*));
            break;
        case ‘d‘:
            printf("%d ", va_arg(ap, int));
            break;
        default:
            assert(0);
        }
    }
    va_end(ap);
    putchar(‘\n‘);
}

int main(void)
{
    char *str = "abc";
    tiny_printf("sdd", "hello", 3, 5);
    return 0;
}

In line 14th, declare the variable AP of type va_list. The va_list type is defined like this:

typedef char *va_list;
In line 15th, Va_start (AP, format) means "point the pointer ap to the next position in parameter format."
Va_arg () Set the AP and parameter types so that the parameters of the variable-length section can be removed in the book order.
The 30th line of Va_end () is just a decoration.


The function of variable length parameter

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.