Possible Duplicate:
When to pass by reference and when to pass by pointer in C++?
What is the difference between passing by reference and passing the value by a pointer?
Pointer and reference can both be used to refer to variable value and to pass it to function by reference rather than by value. Passing by reference is more efficient than passing by value, so the use of pointer and reference is encouraged.
References are usually preferred over pointers whenever we don't need “reseating”. Overall, Use references when you can, and pointers when you have to. But if we want to write C code that compiles with both C and a C++ compiler, you'll have to restrict yourself to using pointers.
When you use pass-by-pointer, a copy of the pointer is passed to the function. If you modify the pointer inside the called function, you only modify the copy of the pointer, but the original pointer remains unmodified and still points to the original variable.
3.1: Pass Class Parameters by Reference What is surprising is that passing a complex object by reference is almost 40% faster than passing by value. Only ints and smaller objects should be passed by value, because it's cheaper to copy them than to take the dereferencing hit within the function.
When you pass a parameter by reference, the parameter inside the function is an alias to the variable you passed from the outside. When you pass a variable by a pointer, you take the address of the variable and pass the address into the function. The main difference is that you can pass values without an address (like a number) into a function which takes a const reference, while you can't pass address-less values into a function which takes const pointers.
Typically a C++ compiler implement a reference as a hidden pointer.
You can change your function into the pointer variant this way:
void flip(int *i) // change the parameter to a pointer type
{
cout << " flip start "<<"i="<< *i<<"\n"; // replace i by *i
*i = 2*(*i); // I'm not sure it the parenthesis is really needed here,
// but IMHO this is better readable
cout << " flip exit "<<"i="<< *i<<"\n";
}
int main()
{
int j =1;
cout <<"main j="<<j<<endl;
flip(&j); // take the address of j and pass this value
// adjust all other references ...
}
For the second part of your question, here is the code.
#include <iostream>
#include <cassert>
using namespace std;
void flip(int *i)
{
cout << " flip start "<<"i="<< i<<"\n";
*i *= 2;
cout << " flip exit "<<"i="<< i<<"\n";
}
int main()
{
int j =1;
cout <<"main j="<<j<<endl;
flip(&j);
cout <<"main j="<<j<<endl;
flip(&j);
cout <<"main j="<<j<<endl;
flip(&j);
cout <<"main j="<<j<<endl;
assert(j==8);
return 0;
}
For the first part of your question, I am new to C++ but I find it useful to pass by pointer when having to return multiple outputs for a function. Or to pass NULL as a parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With