Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Passing variable number of arguments to a C++ function (http://www.go4expert.com/articles/passing-variable-arguments-cpp-function-t17592/)

SaswatPadhi 18May2009 20:27

Passing variable number of arguments to a C++ function
 
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: C++

#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: c++

#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 !

shabbir 19May2009 08:39

Re: Passing variable number of arguments to a C++ function
 
Here is a practical example of it

OutputDebugString with variable number of arguments

shabbir 3Jun2009 09:38

Re: Passing variable number of arguments to a C++ function
 
Nomination this Article for Article of the month - May 2009

debleena_doll2002 5Jun2009 21:49

Re: Passing variable number of arguments to a C++ function
 
By any way map is based on tree only. so what is great in that you are returning as pointer only.

SaswatPadhi 5Jun2009 22:10

Re: Passing variable number of arguments to a C++ function
 
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:

LenoxFinlay 11Jun2009 13:05

Re: Passing variable number of arguments to a C++ function
 
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];
}
?>

SaswatPadhi 11Jun2009 13:13

Re: Passing variable number of arguments to a C++ function
 
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.

shabbir 17Jun2009 18:56

Re: Passing variable number of arguments to a C++ function
 
Vote for this article in Article of the month - May 2009

mayjune 18Jun2009 14:39

Re: Passing variable number of arguments to a C++ function
 
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....

SaswatPadhi 18Jun2009 17:06

Re: Passing variable number of arguments to a C++ function
 
Quote:

Originally Posted by mayjune (Post 49850)
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....

Glad that you liked it. You can just vote for it.

mayjune 18Jun2009 17:16

Re: Passing variable number of arguments to a C++ function
 
i can't ...need to post more... (heres one more ;) )
all the best...

dipakdayanand 12Aug2009 15:34

Re: Passing variable number of arguments to a C++ function
 
Quote:

Originally Posted by SaswatPadhi (Post 49876)
Glad that you liked it. You can just vote for it.

i didnt understand the working of the second program.can anybody explain to me what the function does??

c_user 1Sep2009 22:12

Re: Passing variable number of arguments to a C++ function
 
yup a good thread ....
congrax saswat padhi..

rajanchittil 24Jan2011 13:22

Re: Passing variable number of arguments to a C++ function
 
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


All times are GMT +5.5. The time now is 07:23.