1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Passing variable number of arguments to a C++ function

Discussion in 'C++' started by SaswatPadhi, May 18, 2009.

  1. SaswatPadhi

    SaswatPadhi ~ Б0ЯИ Τ0 С0δЭ ~

    Joined:
    May 5, 2009
    Messages:
    1,343
    Likes Received:
    55
    Trophy Points:
    0
    Occupation:
    STUDENT !
    Location:
    Orissa, INDIA
    Home Page:
    Many of us might have wondered at sometime or the other about how to pass a variable number of arguments to C++ functions : something like a printf function. I don't know how many are aware of this, so I decided to post an article on this topic.

    Background



    When a function is declared, the data-type and number of the passed arguments are usually fixed at compile time. But sometimes we require a function that is able to accept a variable number of arguments. The data-type and/or number of the passed arguments are provided at the run-time.

    Through this article, I will try to show you how to create a C function that can accept a variable number of arguments.

    The secret to passing variable number and type of arguments is the stdarg library. It provides the va_list data-type, which can contain the list of arguments passed into a function.
    The stdarg library also provides several macros : var_arg, va_start, and va_end that are useful for manipulating the argument-list.

    Functions of the macros :
    (1) va_start is a macro used to initialize the argument list so that we can begin reading arguments from it. It takes two arguments : (a) the va_list object which stores the passed arguments, and (b) the last named argument, after which the number of arguments is variable.
    (2) va_arg is the macro used to read an argument from the list. It takes two parameters: (a) the va_list object we created, and (b) a data type. va_arg returns the next argument as this type.
    (3) va_end is a macro that cleans up our va_list object when we're done with it.

    The code



    I will clarify the concept with 2 examples.

    Example 1 : A function accepts variable arguments of known data-type
    (A simple average function, that takes variable number of arguments)

    Code:
    #include <stdio.h>
    #include <stdarg.h>
     
    float avg( int Count, ... )
    {
          va_list Numbers;
          va_start(Numbers, Count); 
          int Sum = 0;
          for(int i = 0; i < Count; ++i )
                Sum += va_arg(Numbers, int);
          va_end(Numbers);
          return (Sum/Count);
    }
    
    int main()
    {
          float Average = avg(10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
          printf("Average of first 10 whole numbers : %f\n", Average);
          return 0;
    }
    Output of the above code is :
    Average of first 10 whole numbers : 4.000000


    Example 2 : A function accepts variable arguments of unknown data-type
    (A simple print function, that takes variable number and variable type of arguments)

    Code:
    #include <stdio.h>
    #include <stdarg.h>
    
    float Print( const char* Format, ... )
    {
          va_list Arguments;
          va_start(Arguments, Format);
          double FArg;
          int IArg;
          for(int i = 0; Format[i] != '\0'; ++i )
          {
                if (Format[i] == 'f')
                {
                      FArg=va_arg(Arguments, double);
                      printf("Caught a float : %.3lf\n",FArg);
                }
                else if (Format[i] == 'i')
                {
                      IArg=va_arg(Arguments, int);
                      printf("Caught an integer : %d\n",IArg);
                }
          }
          va_end(Arguments);
    }
    
    int main()
    {
          Print("This is funny, isn't it ?", 1, 2, 12.1200, 3, 4);
          return 0;
    }
    Output of the above code is :
    Caught an integer : 1
    Caught an integer : 2
    Caught a float : 12.120
    Caught an integer : 3
    Caught an integer : 4


    Hope this article will be useful to you.

    Thanx for reading it ! :happy:

    Good bye and take care !
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,276
    Likes Received:
    364
    Trophy Points:
    83
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,276
    Likes Received:
    364
    Trophy Points:
    83
  4. debleena_doll2002

    debleena_doll2002 New Member

    Joined:
    Feb 5, 2008
    Messages:
    119
    Likes Received:
    0
    Trophy Points:
    0
    By any way map is based on tree only. so what is great in that you are returning as pointer only.
     
  5. SaswatPadhi

    SaswatPadhi ~ Б0ЯИ Τ0 С0δЭ ~

    Joined:
    May 5, 2009
    Messages:
    1,343
    Likes Received:
    55
    Trophy Points:
    0
    Occupation:
    STUDENT !
    Location:
    Orissa, INDIA
    Home Page:
    Can anyone kindly explain to me, what the above post means and how is it (if at all) related to my article ?! :confused:

    PS: I searched for the words "map" and "tree" on this page and found one result each : obviously in the post above. :rofl:
     
  6. LenoxFinlay

    LenoxFinlay Banned

    Joined:
    Apr 15, 2009
    Messages:
    46
    Likes Received:
    0
    Trophy Points:
    0
    unction arguments

    Information may be passed to functions via the argument list, which is a comma-delimited list of expressions.
    PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported, see also the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

    Example #1 Passing arrays to functions
    <?php
    function takes_array($input)
    {
    echo
    "$input[0] + $input[1] = ", $input[0]+$input[1];
    }
    ?>
     
  7. SaswatPadhi

    SaswatPadhi ~ Б0ЯИ Τ0 С0δЭ ~

    Joined:
    May 5, 2009
    Messages:
    1,343
    Likes Received:
    55
    Trophy Points:
    0
    Occupation:
    STUDENT !
    Location:
    Orissa, INDIA
    Home Page:
    Passing arrays as arguments to functions and passing "variable number" of arguments are two different things.

    But, in PHP also, we can pass variable number of arguments to a func. May be I'll write an article on it later.
     
  8. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,276
    Likes Received:
    364
    Trophy Points:
    83
  9. mayjune

    mayjune New Member

    Joined:
    Jun 14, 2009
    Messages:
    817
    Likes Received:
    33
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Pune,Delhi
    awesome article....i wish they taught stuff like these in college...they teach you only what you already know...or you can know on your own with a little effort... sigh....
     
    shabbir likes this.
  10. SaswatPadhi

    SaswatPadhi ~ Б0ЯИ Τ0 С0δЭ ~

    Joined:
    May 5, 2009
    Messages:
    1,343
    Likes Received:
    55
    Trophy Points:
    0
    Occupation:
    STUDENT !
    Location:
    Orissa, INDIA
    Home Page:
    Glad that you liked it. You can just vote for it.
     
  11. mayjune

    mayjune New Member

    Joined:
    Jun 14, 2009
    Messages:
    817
    Likes Received:
    33
    Trophy Points:
    0
    Occupation:
    Student
    Location:
    Pune,Delhi
    i can't ...need to post more... (heres one more ;) )
    all the best...
     
  12. dipakdayanand

    dipakdayanand New Member

    Joined:
    May 31, 2009
    Messages:
    4
    Likes Received:
    2
    Trophy Points:
    0
    i didnt understand the working of the second program.can anybody explain to me what the function does??
     
  13. c_user

    c_user New Member

    Joined:
    Aug 23, 2009
    Messages:
    86
    Likes Received:
    8
    Trophy Points:
    0
    Occupation:
    Php dev
    Location:
    Bhubaneswar
    yup a good thread ....
    congrax saswat padhi..
     
  14. rajanchittil

    rajanchittil New Member

    Joined:
    Jan 24, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I got a good link which explain this concept .Thought of sharing with you people

    Go through learnwithtechies.com which explanins the same concept

    learnwithtechies.com/index.php/component/content/article/4-c/27-how-to-write-functions-with-variable-number-of-arguments-in-c
     

Share This Page