How to pass variable number of arguments to function?

Variable number of arguments can be managed by using the functions va_arg( ), va_start( ) and  va_end( ). The first argument of all these functions is a pointer to a list which is typedefd as va_list. The following program demonstrates how to define a function which can accept variable number of arguments. We can pass variable number of strings to the function messages( ) which prints all the strings.

#include <stdio.h>

#include <stdarg.h>

#include <string.h>

void messages ( char *msg, … )

{

int total = 0 ;

va_list lptr ;

char arg[80] = ” ” ;

va_start ( lptr, msg ) ;

puts ( msg ) ;

while ( strcmp ( arg, “” ) )

{

strcpy ( arg, va_arg ( lptr, char * ) ) ;

puts ( arg ) ;

}

va_end ( lptr ) ;

}

main( )

{

messages( “Hello”, “Hi”, “Fine”, “Thankyou” ) ;

}

Subscribe / Share

It's very calm over here, why not leave a comment?

Leave a Reply




Categories

Powered by Yahoo! Answers