Function in C with unlimited arguments?

I want to define a C function that can take an unlimited number of arguments of any data type. For example: printf(), scanf()etc.

Any idea on this?

+5
source share
4 answers

To use a variable number of arguments in C, you need to include a header

#include <stdarg.h>

printf() in C, an example of a function that takes a variable number of arguments.

int printf(const char *fmt, ...)

More here

+8
source

Declare a function as accepting the last argument .... You will need to use macros from <stdarg.h>to access arguments like va_list.

- " printf, ", va_list vprintf, vfprintf 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);
}
+5
void printf(char* format, ...)
{
}

Take a look at Variadic Functions and varargs.hor stdarg.h(depending on the compiler).

+2
source

See heading <stdarg.h>and related documentation.

+1
source

All Articles