vararg.c


/*

  VARARG.C
  ========
  (c) Paul Griffiths 1999
  Email: mail@paulgriffiths.net

  Example of using variable length argument lists

*/


#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>


/*  Forward function declarations  */

int  sum      (int nArgs, ...);
void PrintArgs(char *format, ...);


/*  main() function  */

int main() {
    int a = 5, b = 7, c = 11, d = 13, e = 18, result;

    double db     = 3.45;
    char   ch     = 'x';
    char  *st1    = "Random string";
    char  *st2    = "Another random string";


    /*  Demonstrate usage of sum() function  */

    result = sum(3, a, b, c);
    printf("%d + %d + %d = %d\n", a, b, c, result);

    result = sum(4, a, b, d, e);
    printf("%d + %d + %d + %d = %d\n", a, b, d, e, result);

    result = sum(5, a, b, c, d, e);
    printf("%d + %d + %d + %d + %d = %d\n\n", a, b, c, d, e, result);


    /*  Demonstrate usage of PrintArgs() function  */

    PrintArgs("csds", ch, st1, db, st2);

    return EXIT_SUCCESS;
}


/*  Function returns the sum of a variable number of arguments
    of type int. 'nArgs' should contain the number of arguments  */

int sum(int nArgs, ...) {
    int     result = 0;
    va_list argptr;


    /*  Initialize argument pointer  */

    va_start(argptr, nArgs);


    /*  Loop through arguments and add to result  */

    while ( nArgs-- )
	result += va_arg(argptr, int);


    /*  Clean up nicely and return result  */

    va_end(argptr);
    return result;
}


/*  Outputs the type and contents of a variable number of arguments
    with different types. 'format' should be a string containing one
    character for each argument. For example, if 'format' points to
    the string "csds", it signifies that there are four arguments, and
    that:
        'c' : the first argument is a character
	's' : the second argument is a string
	'd' : the third argument is a double
	's' : the fourth argument is a string
    No other argument types other than the three above are supported
    by this function.                                                  */

void PrintArgs(char *format, ...) {
    int     n = 0;
    va_list argptr;

  
    /*  Initialize argument pointer  */

    va_start(argptr, format);


    /*  Determine and output arguments  */

    while ( format[n] ) {
	switch ( format[n] ) {
	case 'c':
	    printf("Argument %d is a char, and is set to: %c\n",
		   n + 1, va_arg(argptr, char));
	    break;

	case 's':
	    printf("Argument %d is a string, and is set to: %s\n",
		   n + 1, va_arg(argptr, char*));
	    break;

	case 'd':
	    printf("Argument %d is a double, and is set to: %f\n",
		   n + 1, va_arg(argptr, double));
	    break;

	default:
	    printf("Unsupported argument.\n");
	    exit(EXIT_FAILURE);
	}
	++n;
    }


    /*  Clean up nicely and exit  */

    va_end(argptr);
}



Please send all comments, suggestions, bug reports etc to mail@paulgriffiths.net