Variadic function which receive and return variable number of arguments

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: Variadic function which receive and return variable number of arguments

To show: How to create and use the C variadic functions which receive and return variable number of arguments

 

 

/* The variadic function */

#include <stdarg.h>

#include <stdio.h>

 

/* variadic function's prototype, count variable is the number of arguments */

int sum_up(int count,...)

{

va_list ap;

int i, sum;

 

printf("\nI'm in sum_up()...\n");

 

/* Initialize the argument list */

va_start (ap, count);

sum = 0;

 

for (i = 0; i < count; i++)

/* Get the next argument value */

sum += va_arg (ap, int);

 

/* Clean up */

va_end (ap);

 

return sum;

}

 

int main(void)

{

/* This call prints 6 */

printf("In main(), call to sum_up with 3 arguments = %d\n", sum_up(2, 2, 4));

/* This call prints 16 */

printf("In main(), call to sum_up() with 5 arguments = %d\n", sum_up(4, 1, 3, 5, 7));

return 0;

}

 

Output example:

 

I'm in sum_up()...

In main(), call to sum_up with 3 arguments = 6

I'm in sum_up()...

In main(), call to sum_up() with 5 arguments = 16

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index