| ID | CS000898 | Creation date | April 17, 2008 |
| Platform | S60 3rd Edition, FP1 | Tested on devices | Nokia N93 |
| Category | Open C | Subcategory | Files/Data |
| Keywords (APIs, classes, methods, functions): va_list, va_start(), va_arg(), va_end() |
This code snippet shows some simple examples for using a variable argument list in Open C. The variable argument list can be used in situations where a function that will accept any number of arguments is needed. In the function declaration, optional arguments are indicated by three dots (...), that is, an ellipsis.
In order to read optional arguments, do as follows:
It is also possible to write a function that will take the format string and a variable number of arguments by using functions vprintf, vfprintf or vsprintf in your own function implementation.
Note: In order to use this code, you need to install Open C plug-in.
This snippet can be self-signed.
The following libraries are required:
LIBRARY libc.lib
#include <stdarg.h> //va_list, va_start, va_arg, va_end
#include <stdio.h> //printf, fprintf, vfprintf
void display_integers(int number, ...);
double get_average(int number, ...);
void my_printf(char *format, ...);
int main(void)
{
int integer_count = 4;
int double_count = 4;
double average = 0;
char* my_message = "va_list message";
display_integers(integer_count, 1, 2, 3, 4);
average = get_average(double_count, 1.2, 2.3, 3.4, 4.5);
printf( "get_average returned: %f\n", average);
my_printf( "%s\n", my_message);
return 0;
}
void display_integers(int number, ...)
{
int index=0;
va_list arguments;
va_start(arguments, number);
for (index=0; index<number; index++)
{
printf("%d\n", va_arg(arguments, int));
}
va_end(arguments);
}
double get_average(int number, ...)
{
int index=0;
double sum=0;
double avg=0;
va_list arguments;
va_start(arguments, number);
for (index=0; index<number; index++)
{
sum+=va_arg(arguments, double);
}
va_end(arguments);
avg = (sum / number);
return avg;
}
void my_printf(char *format, ...)
{
va_list arguments;
fprintf(stdout, "PRINTING: ");
va_start(arguments, format);
vfprintf(stdout, format, arguments);
va_end(arguments);
}
Three different example functions that take a variable argument list as parameter are executed and results are displayed to standard output.
Open C documentation points a known problem with a variable list of arguments in macros. For example, the following statement causes a compilation error in some cases:
#define DEBUG(a,...)
The suggested solutions to solve this problem according to the documentation is as follows:
#define DEBUG _DEBUG
static inline void _DEBUG (const char *a, ...) { }