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.