tags:

views:

104

answers:

5

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;
}
+3  A: 

http://www.parashift.com/c++-faq-lite/references.html

Brennan Vincent
Please, don't post links without even WORKING a bit on the answer.
Matthieu M.
Why not? The link explains very clearly and comprehensively how references work in C++... if the OP reads it, he will learn what he needs to know at least as well as he would if I typed out the answer here.
Brennan Vincent
+6  A: 

You would pass the variable by reference:

void sub_function(int y, int& x)
{
   x+=y
}
MarkD
Actually for purposes of readability, it would be better to return the result as a true function: int sub_function(int y, int x) { return (x+=y); }
txwikinger
In the case of an integer, sure. But for a large or user defined type the efficiency of passing by reference would outweigh the readability.
MarkD
+2  A: 

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);
Timo Geusch
+2  A: 

It's called passing a reference:

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

called like:

sub_function(y,x);
Jerry Coffin
A: 

Btw, having sub_function inline will have no impact on perforamce compared to main with KEEP_IN_BIG_FUNC set to 1.

tojas