I want a program that defines a macro that can count the number of arguments and pass them to a function sum
which sums the arguments' values and returns the total. I managed to do it on GCC but I want to achieve it on Visual C++ 14.
#include "stdafx.h"
#include <iostream>
#include <cstdarg>
#define ELEVENTH_ARGUMENT(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, ...) a11
#define COUNT_ARGUMENTS(...) ELEVENTH_ARGUMENT(dummy, ## __VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define SUM(...) sum(ELEVENTH_ARGUMENT(dummy, ## __VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
int sum(int n, ...) {
int sz{ n };
va_list ap;
va_start(ap, n);
int tmp{};
while (--sz)
tmp += va_arg(ap, int);
va_end(ap);
return tmp;
}
int main() {
std::cout << COUNT_ARGUMENTS(4,57,22,10,5,6,2,8,68,24,24,86,89,89,96,86) << std::endl; // 1
std::cout << SUM(5, 57, 4, 5) << std::endl; // 0
std::cout << COUNT_ARGUMENTS(5, 57, 10) << std::endl;// 1
std::cout << std::endl;
std::cin.get();
}
I don't know what's wrong with my code, it always gives me the sum is 0.