I have some code within one function that I want to separate into its own function. I want to do this with as little modification to the original code as possible. Below I have written a noddy example where the code segment is simply “x += y”. I want to take out that code and put it in its own function. With C I have to do this by changing y in to a pointer and then working with that. But I remember reading somewhere (now forgotten) that there is some trick in C++ where I can pass the variable in a way that the code can remain as “x += y”.
FYI: I want to do this process (and perhaps reverse it later) as I am doing some callgraph profiling.
void main()
{
int x = 2;
int y = 5;
#if KEEP_IN_BIG_FUNC
x += y;
#else // put in sub function
sub_function(y,&x);
#endif
printf("x = %d\n",x); // hopefully will print "7"
}
void sub_function(int y,int *x)
{
*x += y;
}
I believe what you’re looking for is a reference. In your example, the function
sub_functionwould then look like this:and you’d call it this way: