#include <iostream>
/* Couple of simple incrementer functions. One BV, one BR. */
void incrementByValue( int n ) { n++; }
void incrementByRef( int &n ){ n++; };
int main( int argc, char* argv[] )
{
/* Reference example */
/* An integer */
int a = 10;
/* A reference to an int. Note, this has to be initialised when declared */
int &a_ref = a;
/* Print our values. They'll be the same */
std::cout << "a is " << a << std::endl;
std::cout << "a_ref is " << a_ref << std::endl;
/* Change a */
a = 5;
/* Print our values again. Note a_ref changes because a has */
std::cout << "a is " << a << std::endl;
std::cout << "a_ref is " << a_ref << std::endl;
/* Call our by value function */
incrementByValue( a );
/* Print a. Note that it's still five.
This is because when we pass an argument to a function, a local copy
of that variable is made. So within the BV function, the variable 'n'
is not the same variable as 'a'. It is a copy that is discarded when
the scope of the function ends */
std::cout << "a is " << a << std::endl;
/* Let's call our by reference function */
incrementByRef( a );
/* Print a. Note that it's changed.
Because we pass by reference, we're not creating a copy in the function,
but rather we're using the instance 'a' that we created in main.
Therefore, any changes within the function will affect 'a'. */
std::cout << "a is " << a << std::endl;
return 0;
}
Your latter example, int &f (int &a) is bad in my books. Others may disagree, but I'd strongly recommend that you don't return references from functions. For example, if you're returning a reference to an object that is local to the function, the reference is referring to nothing as the variable is destroyed when you leave the scope of the function.
Ignore that, I misread the code as a function prototype. It's not.