Reputation: 67
I have a function defined with several parameters passed by value. Both the function and inputs for the parameters depend on a common global variable. I need some way to get my function to re-evaluate the inputs of its parameters while executing within its own scope. Here is a simplified version of the code.
#include <iostream>
using namespace std;
int Sum(int arg1, int from, int to);
int i;
int func();
int main(int argc, char *argv[])
{
Sum(func(), 0, 10);
return 0;
}
int Sum(int arg1, int from, int to)
{
int out = 0;
for (i = from; i <= to; i++)
{
out += arg1;
cout << "arg1 = " << arg1 << ", out = " << out << endl;
}
return out;
}
int func()
{
return i;
}
Some highlights:
* Here I am trying to update the input values for parameter arg1 on function Sum().
Normally, I would solve this problem by defining the parameter by reference (in this case, the parameter is arg1 in function Sum).
However, because the method in which I use this function normally involves combining multiple input values inline, I have to pass by value.
Is there some way to define a temporary unnamed function inline with the inputs for Sum? Then I could pass parameters by reference and solve my troubles. Or any other ideas for how to make this work?
Thanks!
Upvotes: 1
Views: 2991
Reputation: 17946
This is a place you could use a function pointer. Instead of passing func()
, you pass simply func
, and call it from within your function:
int Sum(int (*func_arg1)(void), int from, int to)
{
int out = 0;
for (i = from; i <= to; i++)
{
int arg1 = func_arg1();
out += arg1;
cout << "arg1 = " << arg1 << ", out = " << out << endl;
}
return out;
}
The syntax for function pointers is a bit unusual in C and C++. The declaration int (*func_arg1)(void)
declares a symbol named func_arg1
that is a pointer to a function taking no arguments, but returning int
. In this case, that symbol is also the first argument of Sum
.
The only other changes you need to make to your program are the prototype for Sum
to match the function above, and to call Sum
as follows:
Sum(func, 0, 10);
Upvotes: 1