Use of variable parameters in C Language

Source: Internet
Author: User

1. A function is generally called with fixed parameters. To call a variable parameter, several macro definitions declared in the stdarg. h library must be used.

2. Definition

In the include file of VC ++ 6.0, there is an stdarg. h header file, which has the following macro definitions:
# 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

3. Implementation of Variable Parameter Functions

# Include <stdio. h>
# Include <stdarg. h>
# Include <iostream>
Using namespace std;

Void UartPrintf (char * fmt ,...)
{
Char buffer [80];
Char cnt;
Va_list argptr; // defines a va_list pointer.
Va_start (argptr, fmt); // obtain the first optional parameter address, that is, a parameter after fmt.
Vsprintf (buffer, fmt, argptr); // output parameters starting with argptr to the buffer in the format of fmt to form an array
UartStr (buffer); // print the data in the buffer in the form of a serial port
}

Int main ()
{
UartPrintf ("% c % d % s % c", 'C', 45, "This a test ");
Return 0;
}
4. Through the above example, the serial port printing function can have the printf effect. You do not need to write functions that recognize formats such as % c, % d, and % s, and simply output them according to the standard.

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.