Passing code to a subfunction

I have code inside one function that I want to split into my own function. I want to do this with minimal modification to the source code. Below I wrote an example example where the code segment is simply "x + = y". I want to take out this code and put it in my own function. With C, I have to do this by changing y to a pointer and then working with it. But I remember reading somewhere (now I forgot) that in C ++ there is some kind of trick where I can pass a variable in such a way that the code can remain as "x + = y".

FYI: I want to make this process (and possibly change it later) as I am profiling the charts.

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;
}
+3
source share
5 answers

, . sub_function :

void sub_function(int y, int& x)
{
  x += y;
}

:

sub_function(y, x);
+2

:

void sub_function(int y, int& x)
{
   x+=y
}
+5

This trick is referred to as passing by reference. C ++ Frequently Asked Questions. There is a good section here:

https://isocpp.org/wiki/faq/references

+3
source

He called the link transfer:

void sub_function(int y, int &x) { 
    x += y;
}

called:

sub_function(y,x);
+2
source

Btw having a sub_function inline will not affect perforamce compared to the main one with KEEP_IN_BIG_FUNC set to 1.

0
source

Source: https://habr.com/ru/post/1752867/


All Articles