Click to See Complete Forum and Search --> : Passing # of Arguments
80Degrees
March 2nd, 2006, 11:20 AM
I was wondering if there were a function to pass the # of arguments in a parameter to a value of a variable.
For instance, lets say I want a program that does averages, the main function collects the #'s, and then theres a getAvg function which does the math
Is there a way for one of the arguments in getAvg to be the # values being passed to it?
laserlight
March 2nd, 2006, 11:24 AM
You could store the numbers in say, a std::vector and when the data collection is done, just calculate the average of the numbers in the container.
stober
March 2nd, 2006, 12:18 PM
you could write getAvg() to use a variable number of arguments, but the std::vector is a lot better and easier to implement solution for c++ programs. There must be at least one non-variable argument. and you need to devise for that function to know where the last argument is -- maybe pass -1 or something else that will not occur normally in the other arguments. for variable arguments you need to use functions in stdarg.h (http://msdn2.microsoft.com/en-us/library(d=robot)/kb57fad8.aspx) . Scroll down the page of that link and you will find some example programs.
int getAvg(int a, ...);
int main()
{
int n = getAvg(1,2,3,4,5,6,-1);
}
exterminator
March 3rd, 2006, 12:26 AM
Variadic functions (http://www.gnu.org/software/libc/manual/html_node/Variadic-Functions.html)
laserlight
March 3rd, 2006, 01:17 AM
The problem I see is that for "the main function collects the #'s" to work, there must be some way to store the numbers. Or, if the average is the arithmetic mean, one can just sum and keep a counter of the number of numbers input, then divide. That doesnt even need a container (aside from the sum), but "average" here is rather vague.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.