Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic function arguments in C++, possible?

Tags:

c++

function

I am little new to C++, I have one doubt in variable argument passing. As I mentioned in a sample code below ( This code won't work at all, just for others understanding of my question I framed it like this), I have two functions func with 1 parameter and 2 parameters(parameter overloading). I am calling the func from main, before that I am checking whether I needs to call 2 parameter or 1 parameter. Here is the problem, as I know I can call two functions in respective if elseif statements, but I am curious to know whether I can manage with only one function. (In below code I am passing string not int, as I mentioned before this is just for others understanding purpose.

#include<iostream.h>
#include <string>

void func(int, int);
void func(int);

void main()
{
   int a, b,in;

   cout << "Enter the 2 for 2 arg, 1 for 1 arg\n";
   cin << in;

   if ( in == 2)
   { 
      string pass = "a,b";
   }
   elseif ( in == 1)
   {
      string pass = "a";
   }
   else
   {
      return 0;
   }

   func(pass);

   cout<<"In main\n"<<endl;
}

void func(int iNum1)
{
   cout<<"In func1 "<<iNum1<<endl;
}

void func(int iNum1, int iNum2)
{
   cout<<"In func2 "<<iNum1<<" "<<iNum2<<endl;
}
like image 964
duslabo Avatar asked Jul 24 '26 23:07

duslabo


2 Answers

You may use stdarg method as explained by Ronald. Or you could use a function that takes a vector of arguments. Push the arguments to the vector first and then call following func:

func(const vector<int>& argv) {
  for (vector<int>::const_iterator iter = argv.begin(); iter != argv.end(); ++iter) {
    // Get the arguments
  }
  // Do what you want ...
}
like image 102
ozox Avatar answered Jul 27 '26 11:07

ozox


I believe you may be interested in looking at the stdarg library. A sample usage is as follows,

#include <cstdarg>
#include <iostream>

using namespace::std;

void func(int, ...);

int main(void) {
  func(1, 10);
  func(2, 20, 30);
  return 0;
}

void func(int num_args, ...) {
  va_list ap;

  va_start(ap,num_args);
  for(size_t loop=0;loop<num_args;++loop) {
    if(loop>0) cout << " ";
    cout << va_arg(ap,int);
  }

  va_end(ap);

  cout << endl;
}
like image 21
Ronald Yeung Avatar answered Jul 27 '26 11:07

Ronald Yeung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!