C + + variable parameter function

Source: Internet
Author: User

Translated from 8940092

Implements the variable parameter function for C/C + + language.

Variable parameter function: void Fun (para,...)

The variable parameter function must have a fixed parameter.

 

defined in header file stdarg.h Three macros can be used:     void    Va_start (va_list    arg, prev_ param   );     

type    va_arg (va_list    arg, type    );     

void    va_end (va_list    arg   );    

 
va here is the meaning of variable-argument (variable parameter) .      

Then the implementation of the variable parameter function becomes relatively simple.

The general parameter function processing process:

① defines a va_list variable to be set to VA

The ② call Va_start () causes the VA to store the address of a fixed parameter before the variable parameter function.

③ constantly calls Va_arg () to make the VA point to the next variable parameter.

④ Last Call to Va_end () indicates that the argument processing is complete.

The principle is: the parameters of the function are stored in memory from the low address to the high address.

Look at an example: imitating the implementation of PRITNF:

#include <iostream>#include<stdarg.h>#include<string.h>using namespacestd;voidFuncChar*c,...) {        intI=0; Doubleresult=0;    Va_list Arg; //va_list VariableVa_start (ARG,C);//arg points to fixed parameter C     while(c[i]!=' /'){                if(c[i]=='%'&&c[i+1]=='D') {printf ("%d", Va_arg (ARG,int)); I++; }        Else if(c[i]=='%'&&c[i+1]=='F') {printf ("%f", Va_arg (ARG,Double)); I++; }            Else {            Charnewc[2] = {C[i]};//converts a character to a string output, or you can use Putchar ()printf"%s", NEWC); } I++; } va_end (ARG);}intMain () {intI= -; Doublej=100.0; printf ("%d be equal%f\n", i,j); Func ("%d be equal%f\n", i,j); }

C + + variable parameter function (RPM)

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.