Transfering code to a sub function
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;
}
You would pass the variable by reference:
void sub_function(int y, int& x)
{
x+=y
}
This trick is called passing by reference. The C++ FAQ Has a good section on references here:
https://isocpp.org/wiki/faq/references
I believe what you're looking for is a reference. In your example, the function sub_function
would then look like this:
void sub_function(int y, int& x)
{
x += y;
}
and you'd call it this way:
sub_function(y, x);
It's called passing a reference:
void sub_function(int y, int &x) {
x += y;
}
called like:
sub_function(y,x);
Btw, having sub_function inline will have no impact on perforamce compared to main with KEEP_IN_BIG_FUNC set to 1.
精彩评论