1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - Lesson Six - About Functions

By , About.com Guide

5 of 6

Learn more about how to write and use variadic functions.

Variadic functions

The printf() function allows multiple arguments. It is a variadic function. If you want to write variadic functions, you use ellipsis ( ... ) as a parameter.
int sumupparameters(int value,...) ;

Getting the values from variadic Parameters

From the standard header files (see the first Page of this lesson), we use <stdarg.h>. This provides macros that let you access the parameters.

Macros There are three macros defined in <stdarg.h> and one type va_list.

  • va_start( va_list ap, lastarg) ; // Start with first parameter after lastarg
  • va_arg(va_list ap,type) ; // fetch value of type 'type'
  • va_end(va_list ap) ; // must do to complete
va_list holds the list of parameters.
#include <stdarg.h>
#include <stdio.h>
#include "stdafx.h"

double total ( int numvalues, ... )
{
va_list values;
double temptotal = 0;
va_start ( values, numvalues ) ;
while ( numvalues-- )
{
temptotal += va_arg ( values, double ) ;
}
va_end ( values ) ;
return temptotal;
}

int main()
{
printf( "%f\n", total ( 4, 1.0, 5.9, 107.3, 95.8 ) ) ;
return 0;
}
On the next page : Learn how this code works.
Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Learn about Variadic Functions

©2009 About.com, a part of The New York Times Company.

All rights reserved.