I’m trying to make a simple addition calculator in C to learn how to work with indefinite arguments. The following compiles correctly but the output is always incorrect and I don’t know enough to debug it. Any pointers would be great.
#include <stdio.h>
#include <stdarg.h>
int calculateTotal(int n, ...)
{
//declartion of a datatype that would hold all arguments
va_list arguments;
//starts iteration of arguments
va_start (arguments, n);
//declarion of initialization for 'for loop'
//declation of accumulator
int i = 0;
int localTotal = 0;
for(i; i < n; i++)
{
//va_arg allows access to an individual argument
int currentArgument = va_arg(arguments, int);
localTotal += currentArgument;
}
//freeing the declaration of the datatype that holds the information
va_end(arguments);
return localTotal;
}
int main()
{
int total = calculateTotal(56,7,8);
printf("Total > %d\n",total);
return 0;
}
You are passing 56 as the first argument instead of 2. The function then interprets 56 as the number of arguments, and continue reading its “parameters” past the initialized area.
When you modify the call to pass 2, the result returned from the function is 15.