Use of variadic function

Source: Internet
Author: User
Tags variadic

Recently looking at <the C programming language> K&r

7.3 Chapter Variable-length Argument Lists variable length parameter list, take a note of usage

1. header files to use <stdarg.h>

Contains some macro (marco) definitions used to traverse (step through) variable-length parameter lists

2. Type Va_list:refer to all argument in turn (VA is the abbreviation for variadic arguments)

Va_list ap; /* Declare va_list type of pointer ap */

3. Macro Va_start

Usage: Va_start (va_list, char *);

Initializes a pointer to the Va_list type, pointing to the first unnamed parameter in the list, and must first call it

Va_start to use the last named argument, so at least one named parameter in the function argument list

4.va_arg

Usage: va_arg (va_list, type name); /* type name may be int double these types */

Returns a parameter that points the pointer to the next parameter

5.va_end

Usage: va_end (va_list);

The aftermath of Va_start's work

6.va_cpy

Usage: va_copy (va_list src, va_list dest);

Sample Code : (Excerpt from: Man page)

Simple sequential invocation of the va_list va_start va_arg va_end

/* The function foo takes a string of format characters and prints out the argument associated
* with all format character based on the type.
*/
#include <stdio.h>#include<stdarg.h>voidFoo (Char*FMT, ...) {va_list ap; intD; CharC, *s;       Va_start (AP, FMT); while(*FMT)Switch(*fmt++) { Case 's':/*string*/s= Va_arg (AP,Char*); printf ("string%s\n", s); Break; Case 'D':/*int*/D= Va_arg (AP,int); printf ("int%d\n", D); Break; Case 'C':/*Char*/ /*need a cast here since Va_arg only takes fully promoted types*/C= (Char) Va_arg (AP,int); printf ("Char%c\n", c); Break; } va_end (AP); }



attached : Linux can be used under the Man command to view Stdarg, Va_start, Va_arg, Va_end, va_copy

Mans 3 Stdarg

Use of variadic function

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.