Simple use of va_list

Source: Internet
Author: User

# Include <stdarg. h>

# Define _ INTSIZEOF (n) (sizeof (n) + sizeof (int)-1 )&~ (Sizeof (int)-1 ))
# Define va_start (ap, v) (ap = (va_list) & v + _ INTSIZEOF (v) // The first optional parameter address
# Define va_arg (ap, t) (* (t *) (ap + = _ INTSIZEOF (t)-_ INTSIZEOF (t) // The next parameter address
# Define va_end (ap) (ap = (va_list) 0) // set the pointer to invalid


Sample Code
Void arg_test (int I ,...);
Int main (int argc, char * argv [])
{
Int int_size = _ INTSIZEOF (int );
Printf ("int_size = % d \ n", int_size );
Arg_test (0, 4 );

Arg_cnt (4, 1, 2, 3, 4 );
Return 0;
}
Void arg_test (int I ,...)
{
Int j = 0;
Va_list arg_ptr;

Va_start (arg_ptr, I );
Printf ("& I = % p \ n", & I); // print the address of parameter I in the stack
Printf ("arg_ptr = % p \ n", arg_ptr );
// Print the arg_ptr address after va_start,
// It should be higher than the address of parameter I in sizeof (int) bytes
// Arg_ptr points to the address of the next parameter.

J = * (int *) arg_ptr );
Printf ("% d \ n", I, j );
J = va_arg (arg_ptr, int );
Printf ("arg_ptr = % p \ n", arg_ptr );
// Print the address of arg_ptr after va_arg
// It should be higher than the sizeof (int) byte before calling va_arg
// Arg_ptr points to the address of the next parameter.
Va_end (arg_ptr );
Printf ("% d \ n", I, j );
}

Related Article

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.