Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function in C with unlimited arguments?

Tags:

c

I want to define a function in C language which can take an unlimited number of arguments of any datatype. For example: printf(), scanf(), etc.

Any idea on this?

like image 714
Pradeep Avatar asked Dec 30 '10 03:12

Pradeep


1 Answers

Declare the function as taking a ... last argument. You'll need to use the macros from <stdarg.h> to access the arguments as a va_list.

If you just want something "like printf, but with a little extra behavior", then you can pass the va_list to vprintf, vfprintf, or vsprintf.

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

#ifdef __GNUC__
    __attribute__((format(printf, 1, 2)))
#endif
void PrintErrorMsg(const char* fmt, ...)
{
    time_t     now; 
    char       buffer[20];
    va_list    args;

    va_start(args, fmt);
    time(&now);
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", gmtime(&now));
    fprintf(stderr, "[%s] ", buffer);
    vfprintf(stderr, fmt, args);
    fputc('\n', stderr);
    va_end(args);
}
like image 96
dan04 Avatar answered Oct 11 '22 13:10

dan04