Книга: Advanced PIC Microcontroller Projects in C

4.1.4 Variable Number of Arguments

4.1.4 Variable Number of Arguments

The ellipsis character (“...”) consists of three successive periods with no spaces between them. An ellipsis can be used in the argument lists of function prototypes to indicate a variable number of arguments or arguments with varying types. An example of a declaration of a function prototype with ellipsis follows. In this declaration, when the function is called we must supply at least two integer type arguments, and we can also supply any number of additional arguments:

unsigned char MyFunc(int a, int b, ...);

The header file stdarg.h must be included at the beginning of a program that uses a variable number of arguments. This header file defines a new data type called va_list, which is essentially a character pointer. In addition, macro va_start() initializes an object of type va_list to point to the address of the first additional argument presented to the function. To extract the arguments, successive calls to the macro va_arg() must be made, with the character pointer and the type of the parameter as the arguments of va_arg().

An example program is given in Figure 4.12. In this program the function header declares only one parameter of type int, and an ellipsis is used to declare a variable number of parameters. Variable num is the argument count passed by the calling program. The arguments are read by using the macro va_arg(ap, int) and then summed using variable temp and returned by the function.

/*********************************************************************
                PASSING VARIABLE NUMBER OF ARGUMENTS
               ======================================
This program shows how variable number of arguments can be passed to a
function. The function header declares one integer variable and an ellipsis is
used to declare variable number of parameters. The function adds all the
arguments and returns the sum as an integer. The number of arguments is
supplied by the calling program as the first argument to the function.
Programmer: Dogan Ibrahim
File:       VARIABLE.C
Date:       May, 2007
***********************************************************************/
#include <stdarg.h>
/* Function with variable number of parameters */
int Sum(int num, ...) {
 unsigned char j;
 va_list ap;
 int temp = 0;
 va_start(ap, num);
 for (j = 0; j < num; j++) {
  temp = temp + va_arg(ap, int);
 }
 va_end(ap);
 return temp;
}
/* Start of the main program */
void main() {
 int p;
 p = Sum(2, 3, 5);    // 2 arguments. p=3+5=8
 p = Sum(3, 2, 5, 6); // 3 arguments, p=2+5+6=13
}


Figure 4.12: Passing variable number of arguments to a function

Оглавление книги


Генерация: 1.000. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз