CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Feb 2006
    Posts
    162

    Passing # of Arguments

    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?

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Passing # of Arguments

    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.

  3. #3
    Join Date
    Jun 2002
    Posts
    1,417

    Re: Passing # of Arguments

    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 . Scroll down the page of that link and you will find some example programs.

    Code:
    int getAvg(int a, ...);
    
    int main()
    {
       int n = getAvg(1,2,3,4,5,6,-1);
    }

  4. #4
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

  5. #5
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Passing # of Arguments

    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured