Variable Parameter Learning Summary

Source: Internet
Author: User

A function with variable parameters is often encountered at work

The variable parameters currently provided by C are stated as
void function (const char *format, ...);
This allows variable parameters to be used in the function
C provides several macros for using variable parameters
Va_list
Va_start
Va_arg
Va_end
which
Va_list used to define a variable to get a variable parameter pointer
Va_start is used to initialize a pointer defined by va_list
Va_arg to get the true type data for the corresponding pointer
Va_end for emptying the va_list defined pointer

The following is a concrete example of a variable parameter, which can be used to calculate the and of any number of int values
int sum (int number, ...)
{
va_list arg_ptr = NULL;

Va_start (arg_ptr, number);

int sum = 0;

for (int i=0; i<number; i++)
{
Sum + = va_arg (arg_ptr, int);
}

va_end (ARG_PTR);

return sum;
}

2 principle:
Let's see what these macros have done.
typedef char * VA_LIST; This is just a redefinition ...

Get the address of V
#define _ADDRESSOF (V) (& (v))
The size of the integer byte of n, which must be an integer multiple of sizeof (int). If sizeof (n) is 5, _intsizeof (n) is 8 (assuming 32-bit machine)
#define _INTSIZEOF (N) ((sizeof (n) + sizeof (int)-1) & ~ (sizeof (int)-1))
The address of V plus the size of V
#define VA_START (AP,V) (AP = (va_list) _addressof (v) + _intsizeof (v))

To increase the size of the AP and obtain the data of the address of the original AP, forcing the conversion to type T
This corresponds to (* (T *) AP)
(AP + = _intsizeof (t))
This one macro is equivalent to doing two things
#define VA_ARG (Ap,t) (* (t *) (AP + = _intsizeof (t))-_intsizeof (t)))

Give the AP 0
#define VA_END (AP) (AP = (va_list) 0)

Variable Parameter Learning Summary

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.