1

I am attempting to create a function which takes two arguments, but that is remapped by a macro to call a different, hidden function which takes more data than was passed in. The data I will be passing into the hidden function is stuff like __LINE__ and __FILE__ along with the data from the main function.

The problem is that the visible function requires the ability to pass in any number of arguments. The code below is a simplified example of the problem.

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

///////////////////////////////////////////////////////////
// This is what I would like to be able to do
#define average(count, ...) _average(__LINE__, count, ...)
///////////////////////////////////////////////////////////

// The average function
double _average(int _line, int count, ...) {
    // Just a use for the extra variable
    printf("Calculating the average of some numbers\n");
    printf("on line %i\n", _line);

    // The data contained within the "..."
    va_list args;
    va_start(args, count);

    // Sum up all the data
    double sum = 0;
    for (int i = 0; i < count; i++) {
        sum += va_arg(args, int);
    }

    // Return the average
    return sum / count;
}

int main() {
    printf("Hello, World!\n");

    // Currently, this is what I have to do as the method I would prefer doesn't work...
    printf("Average: %f\n", _average(__LINE__, 3, 5, 10, 15));

    // Is there a way to use the above macro like the following?
    // printf("Average 2: %f\n", average(3, 2, 4, 6));

    return 0;
}

If it helps, the output of this code is as follows:

Hello, World!
Calculating the average of some numbers
on line 160
Average: 10.000000
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Pencilcaseman
  • 360
  • 6
  • 16

1 Answers1

3

To define a variadic macro, specify ... in the parameter list and refer to them with __VA_ARGS__:

#define average(count, ...) _average(__LINE__, count, __VA_ARGS__)
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • Note that life gets trickier if you need an empty list after the count — it's doable, but the solutions aren't entirely satisfactory (non-portable using GCC extensions, or losing checking, or ...). But if there'll always be at least one argument after the count, then this is great. You can find a discussion of the issue at [`#define` macro for debug printing in C?](https://stackoverflow.com/q/1644868/15168) – Jonathan Leffler Mar 16 '20 at 22:53