The realization of variable parameter function in C + +

Source: Internet
Author: User

Three functions Va_start, Va_end,va_arg and one type va_list are provided in the C language stdarg.h header file. Using them, we can easily implement a variable parameter function. Let's start with a brief look at these three functions.

Suppose you now have a function called F, whose function is defined as:

void f (int a, int b, ...)

So, inside the function, to get these mutable parameters, you need to take advantage of the three functions of Va_start, Va_arg, and Va_end.

Variables of type va_list can be used to store variable types of variables, which can traverse variable variables;

Va_list AP

Before using the AP, the va_start must be called to associate the AP with the mutable parameter;

Va_start (AP, B);

The second parameter of Va_start is the parameter of the last non-mutable parameter in the function parameter list;

You can then call Va_arg to access the parameters;

Type Va_arg (AP, type);

Once the variable is processed, the va_end should be called once before the program finishes.

void Va_end (AP);
The following program shows a technique used in conjunction with a variadic function and the CSTRING::FORMATV function. This technology is widely used in VC + + programming:

#include <iostream>#include<cstring>#include<string.h>#include<atltime.h>usingnamespace::std;voidwritelogentry (LPCTSTR pstrformat, ...)  {CTime timewrite; Timewrite=Ctime::getcurrenttime (); CString Str= Timewrite.format (_t ("%d%b%y%h:%m:%s-"));  AtlTrace (str);  Va_list args; Va_start (args, Pstrformat); Str.  FORMATV (Pstrformat, args);  AtlTrace (str); return;}intMain () {Writelogentry (_t ("Start program!\n")); Writelogentry (_t ("Program has execute%d lines!\n"),201); Writelogentry (_t ("error%d occured at%d line!\n"),1170, -); Writelogentry (_t ("Program abouted!"));}

The realization of variable parameter function in C + +

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.