cexceptionargument-passing

Creating a proxy function to fprintf in an unobtrusive way?


I'd like to create a proxy to fprintf, like so:

void raise_exception(char *filename, int line, char *format_string, ...) {
    fprintf(stderr, "Exception in `%s`:%d!\n", filename, line);
    fprintf(stderr, format_string, ...);
    exit(EXIT_FAILURE);
}

But what do I put in the place of the second ellipsis? Is it at all possible?

I'd like to simplify it even a bit more like so:

#define RAISE(...) raise_exception(__FILE__, __LINE__, ...)

But I don't think this would work either.

Any ideas? Thanks!

UPDATE

Straight from Wikipedia:

Variable-argument macros were introduced in the ISO/IEC 9899:1999 (C99)

So the define that would do it should look like so:

#define RAISE(...) raise_exception(__FILE__, __LINE__, __VA_ARGS__)

Solution

  • #include <stdarg.h>
    void raise_exception(const char *filename, int line, const char *format_string, ...)
    {
        va_list args;
        fprintf(stderr, "Exception in `%s`:%d!\n", filename, line);
        va_start(args, format_string);
        vfprintf(stderr, format_string, args);
        va_end(args);
        exit(EXIT_FAILURE);
    }